java.lang.Character compareTo(Character anotherCharacter)
Description
Important Notes:
- Specified by compareTo in interface Comparable<Character>
Method Syntax
public int compareTo(Character anotherCharacter)
Method Argument
| Data Type | Parameter | Description |
|---|---|---|
| Character | anotherCharacter | the Character to be compared. |
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.2 and up
Java Character compareTo(Character anotherCharacter) Example
Below is a simple java example on the usage of compareTo(Character anotherCharacter) method of Character class.
package com.javatutorialhq.java.examples;
/*
* This example source code demonstrates the use of
* compareTo(Character anotherCharacter) method of Character class.
*/
public class CharacterCompareToExample {
public static void main(String[] args) {
// initialize 3 Byte object
Character firstValue = new Character('c');
Character secondValue = new Character('a');
Character thirdValue = new Character('c');
// compare the first char to the second
int compareOneTwo = firstValue.compareTo(secondValue);
// compare the first char to the third
int compareOneThree = firstValue.compareTo(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 third 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.
