Possible Duplicate:
How do I compare strings in Java?
why first comparison ( s1 == s2 ) displays equal whereas 2nd comparison ( s1 == s3 ) displays not equal….?
public class StringComparison
{
public static void main( String [] args)
{
String s1 = "Arsalan";
String s2 = "Arsalan";
String s3 = new String ("Arsalan");
if ( s1 == s2 )
System.out.println (" S1 and S2 Both are equal...");
else
System.out.println ("S1 and S2 not equal");
if ( s1 == s3 )
System.out.println (" S1 and S3 Both are equal...");
else
System.out.println (" S1 and S3 are not equal");
}
}
This has to do with the fact that you cannot compare strings with
==as well as compiler optimizations.==in Java only compares if the two sides refer to the exact same instance of the same object. It does not compare the content. To compare the actual content of the strings, you need to uses1.equals(s2).Now the reason why
s1 == s2is true ands1 == s3is false is because the JVM decided to optimize the code so thats1ands2are the same object. (It’s called, “String Pooling.”)Per 3.10.5: Pooling of string literals is actually mandated by the standard.