Java String compare
We can compare String in Java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.
There are three ways to compare String in Java:
- By Using equals() Method
- By Using == Operator
- By compareTo() Method
1) By Using equals() Method
The String class equals() method compares the original content of the string. It compares values of string for equality. String class provides the following 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.
Teststringcomparison1.java
Output:
true true false
In the above code, two strings are compared using equals() method of String class. And the result is printed as boolean values, true or false.
Teststringcomparison2.java
Output:
false true
In the above program, the methods of String class are used. The equals() method returns true if String objects are matching and both strings are of same case. equalsIgnoreCase() returns true regardless of cases of strings.
Click here for more about equals() method
2) By Using == operator
The == operator compares references not values.
Teststringcomparison3.java
Output:
true false
3) String compare by compareTo() method
The above code, demonstrates the use of == operator used for comparing two String objects.
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two String objects. If:
- s1 == s2 : The method returns 0.
- s1 > s2 : The method returns a positive value.
- s1 < s2 : The method returns a negative value.
Teststringcomparison4.java
Output:
0 1 -1
Click me for more about compareTo() method