13: String a = "";
14: a += 2;
15: a += 'c';
16: a += false;
17: if ( a == "2cfalse") System.out.println("==");
18: if ( a.equals("2cfalse")) System.out.println("equals");
Output:
equals
Please correct me if I am wrong...
At line 13 a new String object is created and the reference is stored at a. (a = "")
At line 14 a new String object is created and the reference is stored in a. The previous String object becomes eligible of garbage collection(GC). (a = "2c")
At line 15 a new String object is created and the reference is stored in a. The previous String object becomes eligible of garbage collection(GC). (a = "2cfalse").
Now, the String pool consists of the 2cfalse literal. Therefore, at line-17, shouldn't a == "2cfalse" evaluate to true since they are both pointing to the same object in memory?
However, the program output is just ==. Where did I go wrong? Please can someone explain it to me...
"2cfalse"is only added to the String pool in line 17, when you compareato the literal"2cfalse".The instance referenced by
aprior to line 17 wasn't added to the String pool, so it's not the same instance as the"2cfalse"literal.If you add a call to
a.intern ()just before line 17, the instance referenced byawill be added to the pool (since it wasn't already in the pool), and the condition in line 17 would evaluate to true.If a
Stringequal to"2cfalse"was already in the pool prior to callinga.intern(), you'd have to assign it back toa(i.e.a = a.intern();) in order forato reference the instance stored in the pool.Output: