Java String compareWe 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() MethodThe 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.java Test it NowOutput: 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 Test it NowOutput: 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() method2) By Using == operatorThe == operator compares references not values. Teststringcomparison3.java Test it NowOutput: true false 3) String compare by compareTo() methodThe above code, demonstrates the use of == operator used for comparing two String objects. 3) By Using compareTo() methodThe 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.java Test it NowOutput: 0 1 -1 Next TopicString Concatenation in java « prev next » |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India