11 May String compareTo(String anotherString) method in Java
The compareTo(String anotherString) method in Java compares two strings lexicographically.
Syntax
Let us see the syntax,
1 2 3 |
int compareTo(String anotherString) |
Parameters
Let us see the parameters,
- anotherString – comparison string
Example
The following is an example of compareTo(String anotherString),
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class StudyopediaDemo { public static void main(String args[]) { int value; String msg1 = "Welcome to USA!"; String msg2 = "Welcome to USA!"; String msg3 = "Welcome to Australia!"; String msg4 = "Welcome to Australia!"; System.out.println("String one: " +msg1); System.out.println("String two: " +msg2); System.out.println("String three: " +msg3); System.out.println("String four: " +msg4); value = msg1.compareTo( msg2 ); System.out.println(value); value = msg2.compareTo( msg3 ); System.out.println(value); value = msg3.compareTo( msg4 ); System.out.println(value); } } |
Output
The following is the output,
No Comments