1

When I declare a String using:

String a = new String("Hello");

2 objects are created. 1 object resides in heap and another in String literal pool.

So when I do:

String b = "Hello";

Is a new object created or is "Hello" from String pool referenced to b?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
SDC
  • 161
  • 1
  • 11

2 Answers2

0

A new object is created.

Explanation

  • new String("Hello") creates one object on the heap. It is not stored in the String literal pool. More information here.

  • String b = "Hello" first wants to reuse String "Hello" from the pool, but there is none. So, it will create a new "Hello" String object in the pool and assign your reference to it.

You can read more about String literals in Java Language Specification 3.10.5.

Test

We can test that the references are pointing to different objects:

String a = new String("Hello");
String b = "Hello";
System.out.println(a == b);

Prints false, as expected.

Community
  • 1
  • 1
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
0

I am talking about Java language. I have read in many places that

String a = new String("Hello") 

creates 2 objects. One is in Heap. Could you please let me know where is the other object created?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
SDC
  • 161
  • 1
  • 11