Main difference between == and equals in Java is , "==" is used to compare primitives while equals() method is used to check equality of objects. Another difference between them is that, If both "==" and equals() is used to compare objects than == returns true only if both references points to same object while equals() can return true or false based on its overridden implementation.One of the popular cases is comparing two String in Java in which case == and equals() method return different results. Comparing String with == and equals public class JavaEquals { //since two strings are different object result should be false //since strings contains same content , equals() should return true javaStr = myjava; Output Comparing two strings with == operator: false Comparing two objects with "==" and equals public class JavaEquals { // == should return false //equals should return false because obj1 and obj2 are different // "==" should return true because both obj1 and obj2 points same object Output Comparing two different Objects with == operator: false
public static void main(String[] args)
{
String myjava = new String("My Java Course");
String javaStr = new String("My Java Course");
boolean result = myjava == javaStr;
System.out.println("Comparing two strings with == operator: " + result);
result = myjava.equals(javaStr);
System.out.println("Comparing two Strings with same content using equals method: " + result);
//since both homeLoan and personalLoand reference variable are pointing to same object
//"==" should return true
result = (myjava == javaStr);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);
}
}
Comparing two Strings with same content using equals method: true
Comparing two reference pointing to same String with == operator: true
static boolean result;
public static void main(String[] args)
{
Object obj1 = new Object();
Object obj2 = new Object();
result = (obj1==obj2);
System.out.println("Comparing two different Objects with == operator: " + result);
result = obj1.equals(obj2);
System.out.println("Comparing two different Objects with equals() method: " + result);
obj1=obj2;
result = (obj1==obj2);
System.out.println("Comparing two reference pointing to same Object with == operator: " + result);
}
}
Comparing two different Objects with equals() method: false
Comparing two reference pointing to same Object with == operator: true
Java Thread - How to create Threads in Java?
How to convert ArrayList to Array in Java
What is a Collection ?
How to split a string in Java
How to Sort ArrayList of Object Type in Java?
How to join Multiple String Objects in Java 8
How to Fetch System UUID with Java Program?
What is difference between HashMap and HashSet in Java
How to create Arraylist from Array in Java
How to Convert a Map to a List in Java Example
What is Difference Between "==" and "equals" method in Java
What is Java Collections Framework?