/*** java ==号比较String字符串的地址* <p>* String类代表字符串。 Java程序中的所有字符串文字(例如"abc" )都被实现为此类的实例。* 字符串不变; 它们的值在创建后不能被更改。 字符串缓冲区支持可变字符串。* 因为String对象是不可变的,它们可以被共享** @author silence* @date 2021/6/18*/
public class StringTest {public static void main(String[] args) {String a = "hello";String b = "hell" + "o";String g = "hell";String c = g + "o";String d = new String("hello");final String e = "hell";String f = e + "o";System.out.println("a:" + a);System.out.println("b:" + b);System.out.println("c:" + c);System.out.println("d:" + d);System.out.println("f:" + f + "\n");//a:为字符常量池地址a b:字符常量"hell" + "o" 相加 java会进行优化为 hello等于 b 进行存储//此时字符常量池中已经存储了字符串“hello” 所以b会直接引用常量池的地址值。所以a 和 b 地址值相等System.out.println("a == b " + (a == b));//a:为字符常量池地址a c=变量g("hell") + 字符常量"o" 字符串变量相加 java底层会使用 StringBuilder//或StringBuffer 的append()方法拼接,再调用tostring 存储在堆中 所以和字符常量池a 地址不等System.out.println("a == c " + (a == c));//a:为字符常量池地址a d:new String("hello"); new 关键字每次会在堆中开辟一个新的内存空间存储// 所以d存储的地址是一个新的内存空间,不在字符常量池中。 所以地址不等System.out.println("a == d " + (a == d));//a:为字符常量池地址a f: final String e = "hell" + "o" 因为变量e 使用final修饰所以//是常量不是变量 所以不会调用StringBuilder 拼接。e + a= "hell" + "o"java会优化为hello//此时 f 会引用 a在字符常量池的地址 所以a 和 f 的地址相等System.out.println("a == f " + (a == f));}
}