public class ValueTest {
public static void main(String[] args) {
int i1 = 128;
Integer i2 = 128;
Integer i3 = 128;
// Integer 与int 比较,Integer会自动拆箱
System.out.println(i1 == i2);// true
System.out.println(i1 == i3);// true
Integer i4 = 127; // 等价于 Integer i4= Integer.valueOf(127);
Integer i5 = 127;
Integer i6 = 128;
Integer i7 = 128;
// 缓存 -128 ~ 127,返回的是同一个对象
System.out.println(i4 == i5);//true
// 超过缓存之后返回的是不同对象
System.out.println(i6 == i7);//false
Integer i8 = new Integer(127); // new, 对象不一样
Integer i9 = new Integer(127);
System.out.println(i8 == i9);//false
System.out.println(i8.equals(i9));//true
System.out.println(i4 == i8);//false
}
}
1、Ingeter是int的包装类,int的初值为0,Ingeter的初值为null。
2、无论如何,Integer与new Integer()不会相等。不会经历拆箱过程,i8的引用指向堆,而i4指向专门存放他的内存(常量池),
3、他们的内存地址不一样,使用 == 比较都为false。
4、两个都是非new出来的Integer,使用 == 比较,如果数在-128到127之间,则是true,否则为false
5、两个都是new出来的,==比较都为false。若要比较值是否相等,需使用equals方法进行比较。
6、int和Integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比。
7、Double Float没有缓存的概念
public class ValueTest {
private static String S1 = "abc";
private static String S2 = "a" + "bc";
private static String S3 = "a";
private static String S4 = "bc";
private static String S5 = S3 + S4;
public static void main(String[] args) {
String s1 = "abc";// 常量池
String s2 = "a" + "bc";// 常量池
String s3 = "a";// 常量池
String s4 = "bc";// 常量池
String s5 = s3 + s4; // 非常量池
String s6 = new String("abc");// 非常量池
System.out.println(s1 == s2); //true
System.out.println(s1 == s5);// false
System.out.println(S1 == s1);//true
System.out.println(S1 == S2);//true
System.out.println(S1 == S5);// false
System.out.println(s5 == S5);// false
System.out.println(s1 == s6);// false
s5 = s5.intern();// 如果常量池有返回其句柄
System.out.println(s1 == s5);//true
System.out.println(s5 == S5);// false
}
}