I am not able to understand this When the program runs, str1 -> "Java" (created in a pool, lets say ObjRef1). s1 -> "Ja" (created in a pool, ObjRef2) s2 -> "va" (created in a pool, ObjRef3)
First Line- str1 == s1+s2;
s1 + s2 will form "Java" and since "Java" is already present in the pool (ObjRef1) it must return this reference.
At runtime, s1+s2 will create another String in HEAP and as usually tries to place another Object in Pool. but it finds "java" already there. so does nothing to pool.
str1 -- > pool reference s1+s2 ---> new heap reference
both are not equal.
Additional : Regarding s1+s2 If any one of operands is String reference then Heap Object will be created. If none of them include String reference then tries to create in POOL if doesn't exist.
1) str1 == "Ja"+"va" ---> true, beacuse "Ja" , "va" both String literals(in pool) when concatenated gives "Java" which will be try to create a string in pool. But finds "Java" already created so passes the same reference of str1. thats why true.
2)str1 == s1+s2 ---> false,
Here str1 pointing to String in Pool ---> "Java" in Pool
s1+s2 as we are using the reference , creates a new String in Heap and as usual tries to create another one in pool. but finds "Java" so gives up with creating String in pool. ----> "Java" in Heap(new one)
Hence both references are not equal. so output false.
3)"Java" == "Ja" + "va"
"Java" ---> tries to create one in pool, but gives up as it is already there. and returns the reference of pool string.
"Ja" + "va" --> as explaned in case 1) tries to create "Java" in Pool, and returns the reference of existing pool String.