Java Character compare() Method

Java compare(char x,char y) method is a part of Character class. This method is used to compare the two char values numerically and returns either greater than or less than or equal to zero.

  • 0; if x is equal to y
  • > 0; if x is greater than y and
  • < 0; if x is less than y

It must be noted that the value returned by this method is the same value returned by Character.valueoOf(x).compareTo(Character.valueOf(y)) method.

Syntax:

public static int compare(char x, char y)

Parameters:

The parameters passed are char x and char y which are the two char values to be compared.

Returns:

Returns the value 0, > 0 , < 0 depending upon the value of x and y.

Example 1:

Here, the char values are passed to compare them using the compare() method.

import java.lang.Character;
public class StudyTonight
{    
   public static void main(String [] args)throws Exception
   {   
        char x = 'A';  
		char y = 'B';
		char z = 'A';
		char w = 'D';
		int cmp1 = Character.compare(x, y); //return value<0
		int cmp2 = Character.compare(x, z); //return value=0
		int cmp3 = Character.compare(x, w); // return value>0
		System.out.println(cmp1);
		System.out.println(cmp2);
		System.out.println(cmp3);    
   }
}


-1
0
-3

Example 2:

Here is a general example where the user can enter the characters 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
		{
			char x = sc.next().charAt(0);  
			char y = sc.nextLine().charAt(0);  
			int r =  Character.compare(x, y);    
			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 j k
first character is greater
******************************************
Enter first and second character 1 5
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.