package com.sf.javase.base; public class TestStringIntern { public static void main(String[] args) { String str = new String("hello"); // 这个方法的作用,是先去常量池中查看是否有等于 "hello"的字符串 如果有 返回字符串 // 如果没有 会创建字符串 然后返回字符串的引用地址 str.intern(); // String str1 = new String("hello") + new String(" world"); // str1 = str1.intern(); // String str2 = "hello world"; // System.out.println(str1 == str2); // str1和str2直接比较时 false不相等 // str1从常量池中取值重新赋值后 true相等 // 常量池中保存的是 堆中字符串的地址 // 相等 但是区别在 常量池中保存的是字符串"hello world" String str1 = new String("hello") + new String(" world"); String str2 = "hello world"; str1 = str1.intern(); System.out.println(str1 == str2); // String为什么是不可变的? } }