compareTo() Method in java

Java Programming Language Number Class in java (Article) Number Class in java (Program)

843

Program:


public class CompareToMethodExample {

public static void main(String args[]){
	String s1="hello";
	String s2="hello";
	String s3="meklo";
	String s4="hemlo";
	String s5="flag";
	System.out.println(s1.compareTo(s2));//0 because both are equal
	System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
	System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
	System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
   }
}

Output:

0
-5
-1
2
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.