In
java when two reference variables holding identical data (different instances) are compared with == operator, the answer would be false. But this is slightly different in case of
String. You can see that when you run the following program.
In case we use 'new' operator and create an instance the string variable acts as 'Reference type'.
When a string literal is assigned to a String variable and then compared with String literal it acts as 'Primitive type'.
Why is this so ? Isn't ( String s3 = "hi"; ) a way of instantiating a string ? Or does it altogether have a different semantics ?
----------------------------------------------------------------------------
class Temp {
public static void main(String[] args){
String s1 = new String("hi");
String s2 = new String("hi");
String s3 = "hi";
System.out.println("Value of S1:" + s1);
System.out.println("Value of S2:" + s2);
System.out.println("Value of S3:" + s3);
if(s1 == "hi")
System.out.println("Passed-1");
if(s1 == s2)
System.out.println("Passed-2");
if( s3 == "hi")
System.out.println("Passed-3");
}
}
OUTPUT:
Value of S1:hi
Value of S2:hi
Value of S3:hi
Passed-3