经常碰到比较字符串的题,
eg:
public class StringDemo{
private static final String MESSAGE = "taobao";
public static void main(String [] args){
String a = "tao" + "bao";
Strign b = "tao";
String c = "bao";
System.out.println(a==MESSAGE);
System.out.println((b+c)==MESSAGE);
}
}
程序输出:true;false
1:字符串在java中存储在字符串常量区中;
2:==判断的是对象引用是否是同一个引用,判断字符串相等要用equals
a和MESSAGE是同样的字符串,所以同一份字符串常量在内存中只有一份,因此是同一地址,返回true;
b+c相当于new String(b+c) new了一个String 对象,所以返回false