0

if I write a below code

Scenario-1 [Initially no value in string constant pool]

String s1 = new String("test"); 

then how many object created?

As per my answer : two object created :: one is in string literal pool and other is in heap because of new reference : refer link

why char[] show in refer link

Scenario-2 [Initially no value in string constant pool]

String s1 = "test";
String s2 = new String("test"); 

then how many object created?

As per my answer : three object created :: one is in string literal pool for s1 and second is in heap because of new for s2 and third is char[] for s2 reference : refer link

my answer is correct?? please give me exact idea for this which one is right??

  • hope this answers your question. https://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext – Nakul Gawande May 23 '18 at 05:57
  • You should read [this article](https://www.todaysoftmag.com/article/1706/common-misconception-how-many-objects-does-this-create). – Andy Turner May 23 '18 at 06:28
  • "Scenario-1 [Initially no value in string constant pool]" but there *is* a value in the constant pool already - the literal `"test"`. – Andy Turner May 23 '18 at 06:30
  • in scenario 2 there are 3 object created as per https://stackoverflow.com/questions/19672427/string-s-new-stringxyz-how-many-objects-has-been-made-after-this-line-of is it right? – vishal patel May 23 '18 at 06:59
  • 3 objects including the interned object – Yati Sawhney May 23 '18 at 07:04
  • interned object mean which object?? char[] of string class? as per last comment for scenario 1 there created 3 object also? – vishal patel May 23 '18 at 07:09
  • It would have been clear by now if you would have looked at the `String.java` class Would prefer you to go through the article as well (one suggested by @AndyTurner ) – Yati Sawhney May 23 '18 at 07:26

1 Answers1

0
String s1 = new String("test"); 

JVM creates two objects one on heap and other in constant pool.

String s1 = "test";  //Line 1
String s2 = new String("test"); //Line 2

Line 1 will create an object in constant pool if not already present. Line 2 will create only on heap because one is already there in the pool

If you look at the String class you will find that it initializes a final char[] to create an immutable object but those are confined to instantiation:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    .
    .
    .

    /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this.value = "".value;
    }

    .
    .
    .
}
Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19