-1

I know that there's a String pool which is supposed to keep some created strings in order to not duplicate them. So, if a user wants to create a string with the same value as another string, it won't be created once again (unless the new String() was called), it'll be a reference to the same object. So, my question is why the result of this code is "false false"?

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

What interests me is WHY it's that way, not how to make Java use the pool.

mishkamashka
  • 73
  • 1
  • 6

1 Answers1

1

The correct output for the above code is true false. And the answer to why is string pool there is to simply optimise the memory usage. Whats the point of storing same string every time in heap memory when it can be saved once in a pool and used as long as JVM runs. On the other hand when we are explicitly mentioning java to create an new object String s = new String("test") then it should be created as a new object and should be stored separately in heap(not in the string pool) and thereby can be updated every time when referencing this particular reference ( object s) which will not affect the string pool at all.

Other reason why string pool concept works fine for Strings is associated with the immutability of string in java.

And coming on how to decide on when to use what ?

Java recognises and stores every string literals in string pool . If in your particular usecase there is a lot of playing involved with strings, you should be using literals carefully because it may eventually cause memory error if your code is creating massive amounts of strings in string pool. Also while working with concatenation of heavy string objects, it should be totally avoided.

String a = "Testing"
String b ="this"
String c = "I am " + a + b + "code";

Scenarios like this should be handled with stringbuffer or stringbuilder.

In all, Massive use of string pooling should be avoided. On should switch to string builder instead when using such scenarios. Things like string constants like - "HEADER" , "http://" etc that are being used multiple times are still good to be used as string literals.

javaGroup456
  • 313
  • 1
  • 6
  • 21