Recently I have seen a code like this -
class Test{
public static void main(String[] args){
String s1 = "String1"; //1
String s2 = new String("String2"); //2
System.out.println(s1.equals("String1"));
System.out.println(s1=="String1"); //3
System.out.println(s2.equals("String2"));
System.out.println(s2=="String2"); //4
}
}
and the out put is -
true
true
true
false
So far I know, at point 1 "String1" is placed in String pool and assigned with String type reference variable s1. Isn't there any String object created?
We know a new String object is created at point 2 and at point 4 the expression (s2=="String2") evaluated to false. If a new String object is created at point 1 then how the expression at point 3 (s1=="String1") evaluated to true. And if a new object is not created at point 1 how the expression at point 3 (s1=="String1") evaluated to true?
Thanks in Advance