== operator is used to compare the references of the objects.
public boolean equals(Object o) is the method provided by the Object class. The default implementation uses ==
operator to compare two objects.
But since the method can be overridden like for String class. equals() method can be used to compare the values of two
objects.
String str1 = new String("MyName");
String str2 = new String("MyName");
if(str1 == str2){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
if(str1.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
Output:
Objects are not equal
Objects are equal
Lets look at other snippet:
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
if(str3.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
Objects are equal
Objects are equal
I thinks u r wrong
String str1 = “MyName”;
String str2 = “MyName”;
if(str1 == str2) // also true
Thanks for pointing the mistake.
its a typo error.
I have changed it to
String str1 =new String( “MyName”);
String str2 = new String(“MyName”);
String str1 = “MyName”;
String str2 = “MyName”;
if(str1 == str2) // also true
yes it gives true but these are INTERNED String.
i.e. both str1 and str2 having the same reference.because in pool only one String Litteral r defined to storage and same reference r given to both str1 and str2.
yes thats correct..
yes u…
Thanks for posting this! 🙂
Thanks for posting this! 🙂
Thanks! This was helpful……
this is very helpful for us………………
str1==str2; it compare reference of the str1 and str2
and
str1.equals(str2); it campare to value.
lllllllllllllllllllllllllllllllllllllll
thanks a lot
here is another good link on equals in java, the best part I like is unit test designed to test equals() method.
thanks very much i clearly understood
thank u soo much for this information
enum means??
I every timе spent my half an hour too red this web
site’s posts everyday long ԝіth a mug of coffee.