String对象的不可变性

#String对象的不可变性

package day01;

public class StringDemo1 {

	public static void main(String[] args) {
			String s1 = "123abc";
			String s2 = "123abc";
			String s3 = new String("123abc");
			System.out.println(s1==s2);  //true
			System.out.println(s1==s3);  //false
			s1=s1+"!";
			System.out.println(s1);  //123abc!
			System.out.println(s2);  //123abc
			System.out.println(s1==s2);  //false
			/*
			 * 编译器的一个优化措施:
			 * 当一个计算表达式计算符两遍都是字面量时
			 * 会直接计算结果,然后将结果编译到.class文件中
			 * 所以下面的代码在class文件中的样子是:
			 * String s4 = 123ab"
			 */
			String s4 = "123"+"abc";  
			System.out.println(s4==s2);  //true
			
			/*
			 * 以下代码与上述代码对比:
			 * 创建的字符串变量不是字面量
			 * 因此会重新创建字符串对象"123abc"并指向s5
			 */
			String str1 = "123";
			String str2 = "abc";
			String s5 = str1+str2;
			System.out.println(s5==s2);  //false
			
			

	}

}

猜你喜欢

转载自blog.csdn.net/a771581211/article/details/88239614