Signup/Sign In

Java Character compareTo() method

Java compareTo() method is a part of Character class. This method is used to compare the two Character objects numerically and returns the following values.

  • 0; if the given Character and passed Character are equal.
  • < 0; if the given Character is numerically less than passed Character
  • >0; if the given Character is numerically greater than passed Character.

Syntax:

public int compareTo(Character anotherCharacter )

Parameters:

The parameters passed are the Character objects to be compared numerically.

Returns:

Returns the value 0,> 0 .< 0 depending upon the value of the given object and the passed object.

Example 1:

Here, the Character objects are compared numerically by using the compareTo() method.

import java.lang.Character;
public class StudyTonight 
{  
    public static void main(String[] args) 
    {          
        Character ob1 = 'a';  
		Character ob2 = 'b';  
		Character ob3 = 'a';  

		System.out.println(ob1.compareTo(ob2));  //Output will be less than zero
		System.out.println(ob3.compareTo(ob1)); // Output will be equal than zero  
		System.out.println(ob2.compareTo(ob1));  // Output will be greater than zero
    }  
} 


-1
0
1

Example 2:

Here is a general example where the user can enter the numbers of his choice and get the desired output.

import java.util.Scanner; 
import java.lang.Character;
public class StudyTonight 
{  
	public static void main(String[] args) 
	{      
		Scanner sc = new Scanner(System.in);  
		System.out.print("Enter first and second character ");  
		try
		{
			Character c1 = sc.next().charAt(0);  
			Character c2 = sc.next().charAt(0);  
			int r =  c1.compareTo(c2);    
			if(r > 0)
			{  
				System.out.println("first character is greater");  
			}
			else if(r< 0) 
			{  
				System.out.println("second character is greater");  
			} 
			else
			{  
				System.out.println("both characters are equal");
			}
		}
		catch(Exception e)
		{
			System.out.println("Error!!");
		}          
	}  
}  


Enter first and second character a o
second character is greater
********************************************
Enter first and second character r a
first character is greater

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.