Exercise:
Write a Java Program to differentiate string == operator and equals() method.
Example 1
Click Here to View the Solution!
public class Differentiate {
public static void main(String[] args) {
String name1 = new String("CodeOfCode");
String name2 = new String("CodeOfCode");
System.out.println("Check if two strings are equal");
//check using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator the result is: " + result1);
// check using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals() the result is: " + result2);
}
}
Click Here to View the Output!
Check if two strings are equal Using == operator the result is: false Using equals() the result is: true
Click Here to View the Explanation!
- This program is used to distinguish between the operator
==
and the methodequals()
in Java. - Two string objects are created
name1
andname2
and both contain the same parameterCodeOfCode
that is used to verify the difference. - First, the
==
operator is applied to check whether the reference towards both the string objects is equal and the output is stored in aBoolean variable result1
. In this case, the== operator
will return false. Since, the string objects are not of same references. - Then the method
equals()
is applied to check whether both the string objects hold the same parameter values and the output is stored in theBoolean variable result2
. In this case, theequals()
method will return true because both the string objects are the same i.e. hold contentCodeOfCode
Example 2
Click Here to View the Solution!
public class Differentiate {
public static void main(String[] args) {
String name1 = new String("CodeOfCode");
String name2 = name1;
System.out.println("Check if two strings are equal");
// check using == operator
boolean result1 = (name1 == name2);
System.out.println("Using == operator: " + result1);
// check using equals() method
boolean result2 = name1.equals(name2);
System.out.println("Using equals(): " + result2);
}
}
Click Here to View the Output!
Check if two strings are equal Using == operator: true Using equals(): true
Click Here to View the Explanation!
Here, name1
and name2
both have same references. Hence, name1 == name2
returns true.