The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
Hi... Actually the "=="operator compares the object references(memory locations).So we are getting false in this case.Observe the following program for more details.
public Class StringTest{ public static void main(String args[]){ String s1="DEVARATHNAM"; String s2="DEVARATHNAM"; }//main }//class Explanation: When u declare as String s1="DEVARATHNAM"; // It creates one object in the String pool with identity like 1001(For example). here "s1" reference variable pointing to the "1001" memory location.i.e s1--->1001. In the similar fashion ,"s2" object also created in the String pool with identity like 1002(For example).here "s2" reference variable pointing to the "1002" memory location.i.e s2--->1002. Now u can compare thewe two objects . if (s1==s2)//it means if(1001==1002) so the condition is false.we are getting the inequality of two string objects,eventhough the content is same.
if(s1==s2) { System.out.println("s1 and s2 are same"); } else { System.out.println("s1 and s2 are different"); }
if(s3==s4) { System.out.println("s3 and s4 after using constructor are same"); } else { System.out.println("s3 and s4 after using constructor are different"); }
Yes i agree with Amit thats the write answer to the quetion it just compare the address first ie
class stringcompare { public static void main(String args[]) { String s1="amit"; String s2="amit"; if(s1==s2) { System.out.println("both are same"); else System.out.println("both are different"); } } } output Both are same Because string comparison happens whether both address are same or not