JAVA中的String字符串的存储原理 String表示字符串类型,属于引用数据类型,不属于基本数据类型。在java中随便使用双引号括起来的都是 String 对象。例如"abc",“edf”在java中规定,双引号括起来的字符串是不可更改的,即"abc"不能变成"edf"在JDK中双引号括起来的字符串都是存储在方法区的“字符串常量池”中,因为字符串在开始中使用很频繁,为了提升执行效率,所以把字符串放到了方法区中的字符串常量池 public class StringTest01 { public static void main(String[] args) { //字符串常量池中已经有的字符串对象不会重复创建 //s1 s2中保存的是指向字符串常量池的地址 String s1 = "abcdef"; String s2 = "abcdef" + "xy"; //凡是双引号括起来的在字符串常量池中有一份 //new对象时一定会在堆内存中开辟空间 String s3 = new String("xy"); } } public class StringTest002 { public static void main(String[] args) { //hello已经存储在字符串常量池中了,不会新建 String s1 = "hello"; String s2 = "hello"; //这里双等号比较的是指向字符串常量池的内存地址 System.out.println(s1 == s2); //true String x = new String("xyz"); String y = new String("xyz"); //这里等号比较的是x y指向的堆内存中两个不同的String对象地址 System.out.println(x == y); //false //正确方法应是是使用String类中重写的equals方法对字符串内容进行比较 System.out.println(x.equals(y)); //true String k = new String("testString"); //推荐使用这种格式,因为不会引发空指针异常 System.out.println("testString".equals(k)); //true //可能会引发空指针异常 System.out.println(k.equals("testString")); //true } } 分析 public class StringTest0003 { public static void main(String[] args) { /* 一共创建了3个对象: 方法区字符串常量池中有1个“hello” 堆内存中有2个String对象 */ String s1 = new String("hello"); String s2 = new String("hello"); } }