I have this code
String a="test"; String b="test"; if(a==b) System.out.println("a == b"); else System.out.println("Not True");
And every Java expert knows that here if(a==b) will be passed from the string merge tool .
According to String pooling
Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new String object is created and placed in the pool. JVM keeps at most one object of any String in this pool. String literals always refer to an object in the string pool
And that is why the condition has passed in the above code.
Now here is the question . In the above code, when I added two additional lines a+="1" and b+="1" , now the values โโof String a and b will be Test1 .
The new code will be like this:
String a="test"; String b="test"; if(a==b) System.out.println("a == b"); else System.out.println("Not True"); a+="1"; //it would be test1 now b+="1"; //it would also be test1 now if(a==b) System.out.println("a == b"); else System.out.println("Not True");
Now, after changing the lines, when I placed the check if(a==b) , then it did not pass. I know this is due to the immutable feature of String. But I want to know
1) After the change, does the JVM support their two different objects?
2) Is the JVM called new String() to change any string?
3) Why don't they refer to any, even I tried to call intern() during the change?
Q3 Hint:
a+="1".intern();
b+="1".intern();
source share