2

I have learned that when you have assigned the value with strings, it use a string pools. So that, they are using same address

String S1 = “Hello World”;
String S2 = “Hello World”;

String S3 = “Hello”;
String S4 = “ World”;

System.out.println(S1 == S2); // Returns true

But when I tried to do as follows

S3 = S3 + S4;

And check address with S1...

System.out.println(S1 == S3); // Returns false

Why does it returns false? Why do the JDK doesn’t use the same address with S1 or S2?

Thanks!

Kunanon S.
  • 31
  • 1
  • 6
  • 1
    Explanation of this Question is here: https://stackoverflow.com/questions/45165496/java-string-concatenation-and-interning – Nidhi257 Aug 30 '17 at 07:00
  • 1
    The important thing to remember here is that the interning only works on constant expressions. `"Hello World"` is a constant, but `S1` is not unless the `S1` variable is `final`. That means `S3 + S4` isn't a constant (and thus won't be interned) unless S3 and S4 are both constants -- but of course, if S3 is final, then `S3 = S3 + S4` won't compile. – yshavit Aug 30 '17 at 07:03
  • I´m not really sure what you want to know here as comparing two strings with each other using '=' has no real practical relevance. If you want to compare the content of the strings use s1.equals(s3). It will return a boolean (true or false). – Alexander Heim Aug 30 '17 at 07:05
  • To underscore @AlexanderHeim's point: This is certainly an interesting factoid about Java, and nice to understand as a mental exercise -- but it's almost never something you want to rely about (or even care about). For day-to-day comparisons, just use `equals` and you'll be happy. – yshavit Aug 30 '17 at 07:07
  • 1
    System.out.println(S1 == S3.intern());//true [look that link](https://stackoverflow.com/questions/45165496/java-string-concatenation-and-interning) When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. – MehmanBashirov Aug 30 '17 at 07:11

0 Answers0