0

If I have a completely empty String Pool in Java and I do the following, does the string object 'Hello' be added to the string pool.?

String myStr = new String('Hello');

I know that subsequent calls to new String('Hello'); will create a new string object but not add it to the pool, but what about the first time if 'Hello' is not already in the pool?

Edit: Basically, I need to know why the following prints false:

String myStr = new String("Hello");
print(myStr=="Hello");

If, on first call, new String("Hello"); adds Hello to the pool. Then in the comparison code, we are comparing the pool-resident object 'Hello' with the literal 'Hello' (right side of the ==). Therefore, isn't the left side of the == pointing to the same object (in the pool) as the right side?

TheCoder
  • 8,413
  • 15
  • 42
  • 54

4 Answers4

0

Please have a look on below posts. I guess it will give you the best answer for you

What is String pool in Java?

Thx

Community
  • 1
  • 1
Jeyakumar
  • 31
  • 5
0

"Hello" will be added to the String pool when the class containing

String myStr = new String("Hello");

will be loaded. new String() will be an object on heap, its internal char array will point to char array in the pool. It is not new String("Hello") but the class loader who puts "Hello" to the pool

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Yes and no. If you have the literal "Hello" somewhere in your class, it will be added to the string pool when your class is loaded (before your code runs).

But then you create a new instance of String, which is not in the string pool.

So "Hello" != new String("Hello"), but "Hello" == new String("Hello").intern()

That means new String("Hello") can never add this this new instance to the String Pool, because there is already a "Hello" there.

And no new String(String s) does not add the String to the String Pool; why would it be useful to add e.g. user input to the String Pool?

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
0

In Java '==' operator is used to check the reference of the objects and not the content of the objects it self if not used with a primitive data type. Therefore in your case the myStr and the "Hello" are two different objects in the memory that is why it is returning false. on the other hand if you want to compare the contents of the objects use the equals() method i.e.

print(myStr.equals("Hello")); this statement will return true.

user_CC
  • 4,686
  • 3
  • 20
  • 15