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:
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:
Teststringcomparison1.javaTest it Now
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.javaTest it Now
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.javaTest it Now
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:
Teststringcomparison4.javaTest it Now
Click me for more about compareTo() method
0 1 -1
« prev next »