String compareTo(String anotherString) method in Java

The compareTo(String anotherString) method in Java compares two strings lexicographically.

Syntax

Let us see the syntax,

int compareTo(String anotherString)

Parameters

Let us see the parameters,

  • anotherString – comparison string

Example

The following is an example of compareTo(String anotherString),

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,

Java String compareto method lexicographically

String compareTo(Object o) method in Java
String compareToIgnoreCase() method in Java
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment