java中的字符串。 String类是不可变的,对String类的任何改变,都是返回一个新的,String类对象
public class Test {
public static void main(String args[])
{
String s1 = "a"; //String直接创建
String s2 = "b"; //String直接创建
String s3 = "ab";//String直接创建
String s4 = "ab";
System.out.println("s3==s4? "+ (s3==s4)); //相同引用
String s5 = "a"+"b";
System.out.println("s3==s5? "+ (s3==s5));//相加为俩个常量,编译器优化,s5="a"+"b"优化为s5="ab"
String s6 = s1+s2;//俩个变量相加,编译器无法优化
System.out.println("s3==s6? "+ (s3==s6));
String s7 = new String("ab");//String对象创建
System.out.println("s3==s7? "+ (s3==s7));
final String s8 = "a" ;
final String s9 = "b" ;
String s10 = s8 + s9;//由于是final类型编译器进行了优化所以相同。
System.out.println("s3==s10? "+ (s3==s10));
//s3==s4? true
//s3==s5? true
//s3==s6? false
//s3==s7? false
//s3==s10? true
}
}
如下图所示
图解.png