Java Character compare() Method
Example
Compare two characters:
public class Main {
public static void main(String[] args) {
System.out.println(Character.compare('A', 'B'));
System.out.println(Character.compare('B', 'B'));
System.out.println(Character.compare('C', 'B'));
}
}
Definition and Usage
The compare() method compares two characters by their number in Unicode (the standard list that gives every character a number). For example, 'A' is 65 and 'B' is 66.
It returns 0 if the characters are equal, a number less than 0 if the first character comes before the second, and a number greater than 0 if it comes after the second.
Tip: Uppercase letters come before lowercase letters, because they have smaller numbers. For example, 'Z' comes before 'a'.
Syntax
public static int compare(char x, char y)
Parameter Values
| Parameter | Description |
|---|---|
| x | Required. The first character to compare. |
| y | Required. The second character to compare. |
Technical Details
| Returns: | An int: 0 if the characters are equal, less than 0 if x comes first, and greater than 0 if y comes first. |
|---|
Related Pages
❮ Character Methods