✏️ Explanatory Question

[String]

Question:

How many String objects are created in the following snippet? Justify your answer.

String s1 = "Gujarat";

String s2 = new String("Gujarat");

String s3 = new String("Gujarat");

String s4 = "Gujarat";

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Answer:

A total of 3 String objects are created.

Explanation:

Java stores string literals in a special memory area called the String Constant Pool (SCP).

Step-by-Step Analysis:

1. String s1 = "Gujarat";

  • The string literal "Gujarat" is created in the String Constant Pool.
  • 1 object created.

2. String s2 = new String("Gujarat");

  • The literal "Gujarat" already exists in SCP, so no new literal object is created.
  • new String() creates a new object in heap memory.
  • 1 new object created.

3. String s3 = new String("Gujarat");

  • The literal already exists in SCP.
  • Again, new String() creates another new heap object.
  • 1 new object created.

4. String s4 = "Gujarat";

  • The literal already exists in SCP.
  • No new object is created.

Total Objects Created:

1 object in String Constant Pool
+
2 objects in Heap Memory
=
3 String Objects

Conclusion:

  • String literals are reused from SCP ✅
  • new String() always creates new heap objects ✅
  • Total String objects created = 3