☰ See All Chapters |
String Comparison in Java
There are two different ways to compare objects in Java.
The == operator compares whether two references point to the same object.
The equals() method compares whether two objects contain the same data.
One of the first lessons you learn in Java is that you should usually use equals(), not ==, to compare two strings.
There are three ways to compare String objects:
By equals() method
By = = operator
By compareTo() method
By equals() method
equals() method compares the original content of the string present in string constant pool, whatever may be the objects and references are ignored. It compares values of string for equality. String class provides two methods:
public boolean equals(Object another){} compares this string to the specified object.
public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.
By == operator
The = = operator compares references not values.
compareTo() method
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. The comparison is based on the Unicode value of each character in the strings
Suppose s1 and s2 are two string variables, below table lists out different comparisons:
s1 == s2 | 0 |
s1 > s2 | Positive value |
s1 < s2 | Negative value |
String comparison example
class StringHandling { public static void main(String args[]) { String s1 = "AdiTemp"; String s2 = "AdiTemp"; String s3 = new String("AdiTemp"); String s4 = "Manu M"; String s5 = "aditemp"; System.out.println(s1.equals(s2));// true System.out.println(s1.equals(s3));// true System.out.println(s1.equals(s4));// false System.out.println(s1.equalsIgnoreCase(s5));// true because case is ignored System.out.println(s1 == s2);// true,because both refer to same instance System.out.println(s1 == s3);// false,because s3 refers to instance created in nonpool System.out.println(s1.compareTo(s2));// 0 System.out.println(s1.compareTo(s4));// -12,because s1<s4 System.out.println(s4.compareTo(s1));// 12(because s4>s1 ) } } |
Output:
true true false true true false 0 -12 12 |
All Chapters