DESKTOP-JM545O1_20200910-李东鹏

1. 问题

public class StringDemo{
  private static final String MESSAGE="taobao";
  public static void main(String [] args) {
    String a ="tao"+"bao";
    String b="tao";
    String c="bao";
    System.out.println(a==MESSAGE);//true
    System.out.println((b+c)==MESSAGE);//false
  }
}  

MESSAGE和a都是存放于栈内存中的,栈中的数据是共享的,他们指向的是同一个内存地址,并且值都相同(a在编译的时候就已经被编译器优化,合并成了一个字符串),所以返回true;

(b+c)并没有被编译器优化合并,因为二者在编译时并不是确定的值,编译器会考虑到后继可能会进行运算;
相当于new String(b+c) == MESSAGE,对象都是存放于堆内存中,二者是不同的地址,所以返回false;

public class EqualsMethod
{
    public static void main(String[] args)
    {
        Integer n1 = Integer.valueOf(47);
        Integer n2 = new Integer(47);
        System.out.print(n1 == n2);//false
       
    }
}

使用Integer a = 1;或Integer a = Integer.valueOf(1);
在值介于-128至127直接时,作为基本类型。
使用Integer a = new Integer(1); 时,无论值是多少,都作为对象。

2. 吐槽

早上窗口风好大,谁瞌睡可以来我这吹吹。