假设以下是一段代码,创建了多少字符串对象以及在哪里(StringPool 或堆内存)提及指向适当对象的引用。
String s1 = "abc";
String s2 = s1;
String s3 = new String("abc");
String s4 = s3;
假设以下是一段代码,创建了多少字符串对象以及在哪里(StringPool 或堆内存)提及指向适当对象的引用。
String s1 = "abc";
String s2 = s1;
String s3 = new String("abc");
String s4 = s3;
总共 2 个创建的元素(除了它们的参考):
String
池内存中的1 =>"abc"
String
对象 => new String("abc");
(“abc”仍指"abc"
池中的第一个)。其他人只是参考现有的。
不再 ;)
2 个对象和 4 个引用
String s1 = "abc";
// An object with value"abc" is created; s1 is a reference variable pointing to the newly created object
String s2 = s1;
//Only reference variable s2 is created; It will point to the existing object
String s3 = new String("abc");
//A NEW object is created irrespective of the value. Thumb rule is whenever there is a new operator an "Object" will be created. Reference variable S3 is made to point the newly created object
String s4 = s3;
//Only reference variable s4 is created, and the explanation is similar to ref variable s2
String s1 = "abc";
变量 s1 将引用从字符串常量池引用的字符串文字 hi,如果我们谈论
String s2 = s1;
它们都指的是存储在字符串池中的相同值。
String s3 = new String("abc");
这将在运行时创建一个新字符串。
在第一种情况下,所有字符串文字都是在 JVM 中加载类时创建的。在几秒钟的情况下,字符串对象是在执行 new String() 时创建的。
String s4 = s3;
它们都指的是存储在堆中的同一个对象。
您可以在以下链接中找到有关字符串常量池的好教程
http://www.thejavageek.com/2013/06/19/the-string-constant-pool/
我认为在堆内存中创建了两个对象 s1 和 s3。s2 和 s4 是参考。
将创建两个 String 对象。“abc”将在池内存中创建。实际上 new String("abc") 将创建两个 String 对象,但由于 "abc" 已经在池中,因此不会再次创建。因此语句 new String("abc") 将创建 1 个对象,并将指向字符串文字 "abc" 。