How many objects does new String("India") create in Java?
Up to two. The literal "India" goes into the string pool if it is not already there, and new String(...) always creates a separate object on the heap. So two objects the first time, and one if the pool already had the literal.
Explain it simply
Imagine a college photocopy shop with one master copy of a notice on its wall (the pool). Writing new String("India") is like asking for a fresh photocopy to carry home. The master copy stays on the wall and you get a second, separate sheet.
Example
String a = "India"; // pool object
String b = "India"; // reuses the same pool object
String c = new String("India"); // new heap object
System.out.println(a == b); // prints: true
System.out.println(a == c); // prints: false
System.out.println(a.equals(c)); // prints: trueWhat to say in the interview
"A literal is stored once in the string pool and reused. The new keyword always builds a new object on the heap, whose contents are copied from the literal. So new String("India") creates one object, plus the pool literal if it did not exist before, which is why the common answer is two. Comparing with == checks references, so I always use equals for content."
Common mistakes
- Answering "always two". If the literal is already in the pool, only one new object is created.
- Using
new String("abc")in real code. It wastes memory with no benefit.