当两个操作数运算时类型不一致才会进行类型的提升,例如 int a=10; long b =20; long c = a+b; a 为 int ,b为long ,最后相加结果为long
强制转换,隐式转换为从“小”往“大”转,强制转换则为 “大”转“小”。例如 int a = 100; byte b = (byte)a; 但是需要注意的是“大”转“小”,有可能出现精度丢失问题。
常见考点
考点一 整数类型包装类
Integer a =128;
Integer b =128;
Integer c =99;
Integer d =99;
System.out.println(a==b);// false
System.out.println(c==d);// true
我们如果用反编译工具可以查出 Integer a = 128; 一个语句在编译后 实现的语句为 Integer a = Integer.valueOf(128); 然后可以看一下 这个方法的源码
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/publicstatic Integer valueOf(int i){// 默认情况 low为 -128 high 为127if(i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i +(-IntegerCache.low)];returnnewInteger(i);}
看此方法的源码以及英文注释已说的很清楚了,会对 -128 至127 数字进行缓存,因此才导致上面的结果。其它的整数类型也同样存在此问题 Byte(all byte values are cached.) Short(This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.) Long( -128 to 127)