Example 1: Java program to differentiate == and equals()
class Main {
public static void main(String[] args) {
String name1 = new String("codemy");
String name2 = new String("codemy");
System.out.println("Check if two strings are equal");
// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);
}
}
Output
Check if two strings are equal Using == operator: false Using equals(): true
In the above example, we have used theĀ ==
operator and equals()
method to check if two strings are equal. Here,
==
checks if the reference to string objects are equal or not. Here, name1 and name2 are two different references. Hence, it returnsfalse
.equals()
checks if the content of the string object are equal. Here, the content of both the objects name1 and name2 is the same codemy. Hence, it returnstrue
.
Example 2: Differentiate == and equals()
class Main {
public static void main(String[] args) {
String name1 = new String("codemy");
String name2 = name1;
System.out.println("Check if two strings are equal");
// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);
}
}
Output
Check if two strings are equal Using == operator: true Using equals(): true
Here, name1 and name2 both are refering to the same object. Hence, name1 == name2
returns true
.