字符串对象创建

时间:2014-10-28 11:18:17

标签: java string heap-memory string-pool

假设以下是一段代码,创建了多少个字符串对象以及where(StringPool或堆内存)提及指向适当对象的引用。

String s1 = "abc";
String s2 = s1;
String s3 = new String("abc");
String s4 = s3;

5 个答案:

答案 0 :(得分:2)

共有2个已创建的元素(参考除外):

    池内存中的
  • 1 String => "abc"
  • 堆上的
  • 1 String个对象=> new String("abc");(" abc"仍指代池中的第一个"abc"

其他人只是引用现有的。

不再;)

答案 1 :(得分:1)

String s1 = "abc";

变量s1将引用从String常量池引用的字符串文字hi,如果我们谈论

 String s2 = s1;

它们都指的是存储在String池中的相同值。

String s3 = new String("abc");

这将在运行时创建一个新的String。

在第一种情况下,在JVM中加载类时会创建所有字符串文字。在几秒钟的情况下,在执行新的String()时会创建字符串对象。

String s4 = s3;

它们都指的是存储在堆中的相同对象。

您可以在以下链接中找到有关字符串常量池的优秀教程

http://www.thejavageek.com/2013/06/19/the-string-constant-pool/

答案 2 :(得分:1)

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

答案 3 :(得分:0)

我认为有两个对象创建了s1和s3,它们存在于堆内存中。 s2和s4是参考文献。

答案 4 :(得分:0)

将创建两个String对象。  " ABC"将在池内存中创建。  实际上新的String(" abc")将创建两个String对象,但是" abc"已经在池中,它将不会再次创建。 所以语句new String(" abc")将创建1个对象,它将指向字符串文字" abc" 。

相关问题