2
public class ConcatenationRuntime {
    public static void main(String[] args) {
        String s1 = "jim";
        String s3 = "j";
        String im = "im";
        s3=s3+= im;
        System.out.println("s3> " +s3);  // jim
        System.out.println(s1==s3);  // line 8
        System.out.println("Hel" + "lo" == "Hello");  // true
    }
}

Why it is printing false on line 8? These are all literals, and two references should point to the same literal in the pool - I'm a bit confused.

Roman C
  • 49,761
  • 33
  • 66
  • 176
lowLatency
  • 5,534
  • 12
  • 44
  • 70

1 Answers1

3

Why it is returning false at line 8,

Because of s3=s3+= im; .
Strings computed by concatenation at runtime are newly created objects on heap with there own reference. This reference is not same as what reference is provided by jim kept in StringPool . Hence s1==s3 is providing false.
But if you intern the String s3 and then the check for equality it gives true. For example:

s3.intern() == s1 => returns true

Why ?
Because interning a String object first checks if the given string literal exists in StringPool or not . If the String literal exists in StringPool it returns the reference to that String literal , else it stores a copy of that string literal in StringPool and returns the reference to it. Since jim is already stored in StringPool , so s3.intern() will simply return the reference to jim stored in Stringpool. And hence we get same references. This makes s3.intern() == s1 to return true.

Vishal K
  • 12,976
  • 2
  • 27
  • 38
  • thanks for answer, but in that case "Hel" + "lo" is concatenation at runtime(as much as I understand), thus line 9 should also give false – lowLatency Mar 30 '13 at 14:20
  • 3
    @Naroji No , it is not concatenation at runtime. While compiling this java file compiler considers it as constant , Since it is the concatenation of two literals not two variables of String – Vishal K Mar 30 '13 at 14:31