基本数据类型及占位
类别 | 名称 | 占位 | 范围 |
---|---|---|---|
整型 | byte | 8 | -127-128 |
整型 | short | 16 | ~ |
整型 | int | 32 | ~ |
浮点型 | float | 32 | ~ |
浮点型 | double | 64 | ~ |
字符 | unicode字符(汉字经过编码后也是2字节) | 16 | ~ |
这里注意一下java的方法数限制为65535个,也主要是因为java使用UNICODE标准字符集,为16位,因此一共能表示2的16次方个字符,即65535个。
运算符及优先级
-
常见运算符及优先级
-
移位运算细解
运算符 | 解释 | 举例 |
---|---|---|
<< | 左移运算符,将运算符左边的数据向左移动运算符右边指定的位数(在低位补0) | 1024<<5 |
>> | 右移运算 符,将运算符左边的对象向右移动运算符右边指定的位数。使用符号扩展机制,也就是说,如果值为正,则在高位补0,如果值为负,则在高位补1. | 1024>>5 |
>>> | "无符号"右移运算 符,将运算符左边的对象向右移动运算符右边指定的位数。采用0扩展机制,也就是说,无论值的正负,都在高位补0. | 1024>>>5 |
System.out.println(Integer.toBinaryString(1024));
System.out.println(Integer.toBinaryString(-1024));
System.out.println(Integer.toBinaryString(1024>>5));
System.out.println(Integer.toBinaryString(-1024>>5));
System.out.println(Integer.toBinaryString(1024>>>5));
System.out.println(Integer.toBinaryString(-1024>>>5));
System.out.println(Integer.toBinaryString(1024<<5));
System.out.println(Integer.toBinaryString(-1024<<5));
10000000000
11111111111111111111110000000000
100000
11111111111111111111111111100000
100000
111111111111111111111100000
1000000000000000
11111111111111111000000000000000
注:x<<y 相当于 x*2y ;x>>y相当于x/2y
从计算速度上讲,移位运算要比算术运算快。
如果x是负数,那么x>>>3没有什么算术意义,只有逻辑意义。
- 赋值运算符
自动装箱和拆箱
- 自动装箱和拆箱测试
Integer total = 99;
int totalprim = total;
使用javap可以看到装箱和拆箱的过程
下面这些代码片段仅供参考
private final int value;
public Integer(int value) {
this.value = value;
}
public Integer(String string) throws NumberFormatException {
this(parseInt(string));
}
private static final Integer[] SMALL_VALUES = new Integer[256];
public static Integer valueOf(int i) {
return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
}
public int intValue() {
return value;
}
自动装箱
过程也就是创建对象的过程并且赋值,因此频繁的装箱过程就存在了性能消耗的问题
自动拆箱
的过程则直接返回value值
这里有个问题就是执行Integer 执行valueOf的时候如果数值大于等于128 小于等于-128创建新对象,否则用SMALL_VALUES中已存在对象,而Double确是每次都创建对象
Integer派别:Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
Double派别:Double、Float的valueOf方法的实现是类似的。每次都返回不同的对象。
public static Double valueOf(double d) {
return new Double(d);
}
关于装箱和拆箱有以下几个问题
1、类型匹配问题
Integer num1 = 100;
int num2 = 100;
Long num3 = 200l;
//得到数值200
System.out.println(num1 + num2); //200
//两个类型一样数值相等 结果为true
System.out.println(num3 == (num1 + num2)); //true
//类型不一样数值不等结果false,参考下面的Long的equals的方法先比较类型在比较数值
System.out.println(num3.equals(num1 + num2)); //false
public boolean equals(Object o) {
return (o instanceof Long) && (((Long) o).value == value);
}
- 编译和运行问题
下面这个结果在编译的时候不会报错,但是在执行的时候就会报NullPointException 因为发生了拆箱的过程
Integer integer100=null;
int int100=integer100;