Java String compareTo example
String class CompareTo method example
String class compareTo method example:- This method returns three different forms of Integers positive, negative and zero as per its judgement procedure.
Syntax:- compareTo(String anotherString)
Here is the code:-
/**
* @(#) CompareToString.java
* CompareToString class demonstrates the working of compareTo() method of String class of lang package
* @version 13-May-2008
* @author Rose India Team
*/
public class CompareToString {
public static void main(String args[]) {
String str = "brain's urge to know takes him into the world of science", str1 = str
.toUpperCase(), str2 = str1.toLowerCase(), str3 = str
.substring(16);
System.out.println();
// method returns positive integers if the String value are same but
// their case is different or simply it returns a positive number when
// String values just follow each other
if (str.compareTo(str1) == 0) {
System.out.println(" " + str.compareTo(str1)
+ "both String variables posses same values");
} else {
System.out.println(str.compareTo(str1)
+ " ----Strings str and str1 differ with their respective value but they can be said as they follow each other as their value differ only in cases");
}
System.out.println();
// method here returns zero(o) that means string taken under process posses
// are equal
if (str.compareTo(str2) == 0) {
System.out.println(str.compareTo(str2)
+ " ----both Strings str and str2 variables posses same values and are equal");
} else {
System.out.println(" "
+ str.compareTo(str2)
+ " ----Strings str and str2 differ with their respective value but they can be said as they follow each other as their value differ only in cases");
}
System.out.println();
System.out.println();
// method compareTo returns negative intgers if either String are not
// equal
if (str.compareTo(str3) == 0) {
System.out.println(str.compareTo(str2)
+ " ----both Strings str and str3 variables posses same values and are equal");
} else {
System.out.println(" "
+ str.compareTo(str3)
+ " ----Strings str and str3 are not said to be equal because for them method returns a negative number");
}
System.out.println();
}
} |
Output of the program:-
32 ----Strings str and str1 differ with their respective value but they can be said as they follow each other as their value differ only in cases
0 ----both Strings str and str2 variables posses same values and are equal
-9 ----Strings str and str3 are not said to be equal because for them method returns a negative number
|
|
|