java.lang.Character compare(char x, char y)

Description

The Character.compare(char x, char y) java method compares two char values numerically. The value returned is identical to what would be returned by:

Character.valueOf(x).compareTo(Character.valueOf(y))

Make a note that the compare(char x, char y) method of Character class is static thus it should be accessed statically which means the we would be calling this method in this format:

Character.compare(method args)

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java compare() method non statically.

Method Syntax

public static int compare(char x, char y)

Method Argument

Data Type Parameter Description
char x the first char to compare
char y the second char to compare

Method Returns

The compare(char x, char y) method of Character class returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y.

Compatibility

Requires Java 1.7 and up

Java Character compare(char x, char y) Example

Below is a simple java example on the usage of compare(char x, char y) method of Character class.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * compare(char x, char y) method of Byte class.
 */

public class CharacterCompareExample {

	public static void main(String[] args) {

		// initialize 3 boolean primitive
		char firstValue = 'c';
		char secondValue = 'c';
		char thirdValue = 'e';

		// compare the first char to the second
		int compareOneTwo = Character.compare(firstValue, secondValue);

		// compare the first char to the third
		int compareOneThree = Character.compare(firstValue, thirdValue);

		// display the comparison result of first
		// and second value
		if (compareOneTwo == 0) {
			System.out.println("First and second value are equal");
		} else if (compareOneTwo > 0) {
			System.out.println("First value is greater than second value");
		} else {
			System.out.println("First value is less than second value");
		}

		// display the comparison result of first
		// and second value
		if (compareOneThree == 0) {
			System.out.println("First and third value are equal");
		} else if (compareOneTwo > 0) {
			System.out.println("First value is greater than third value");
		} else {
			System.out.println("First value is less than third value");
		}

	}

}

Sample Output

Below is the sample output when you run the above example.

java Character compare(char x, char y) example output