On the one hand;
String first = "thing";
String second = "thing";
if(first == second)
System.out.print( "Same things" ); //this is printed
On the other hand;
String first = "thing";
String second = new String("thing");
if(first == second)
{
System.out.print("Same things");
}
else
{
System.out.print("Different things"); //This is printed
}
I know that ” == ” operator is using for the comparison of references of two objects, but in the first example, I compared the values of objects directly. I know this kind of comparison is inexact. But why do I get the message in first example? Is it an indicator that references are the same, or is it occured by a coincidence?
in first example
String poolwas used – if you don’t usenewkeyword – every new instance of String lands on that pool, and if String with same value is created – no new object is made – that one on pool is being used.