String和Integer的特例

String和Integer两个类是final类因此当内存中有要指向的对象时就不会创建,jdk 1.5后有了自动装箱功能,因此可以直接String a="12",Integer b=4;:

public static void main(String[] args) {
		String a="1234";
        String b="1234";
        String c = new String("1234");
        System.out.println(a==b);
        System.out.println(a==c);
        System.out.println(a.equals(c));
        
        Integer m=127;
        Integer n =127;
        Integer m2=128;
        Integer n2 =128;
        System.out.println(m==n);
        System.out.println(m2==n2);
        
   } 

  运行效果为:

true
false
true
true
false

1、自动装箱,当Integer m=3;时候满足Integer-int 映射因此,用new(3)自动装箱。

2 String 是final的不会改变除,一般是引用发生改变。String a="123",时候内存中有“123”,再创建b时候会先判断内存中是否有“123”,有则直接被b引用,不重新创建,而c是new String(),无论内存中是否有“123”,他都重新创建“123”。

3、Integer与String相似,但不同的是当大于127时候即1个字节时就会重新创建对象,而不是引用已有的对象。

原文地址:https://www.cnblogs.com/bokeofzp/p/4746053.html