In this article, we are going to compare characters in Java.
Java provides some built-in methods such compare()
and equals()
to compare the character objects. Although, we can use less than or greater than operators but they work well with primitive values only.
Table of Contents
Compare primitive chars
You can compare primitive chars either using Character.compare()
method or <, > or =
relational operators.
Using compare()
The compare()
method of Characters class returns a numeric value positive, negative or zero.
See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static void main(String[] args){ char a = 'a'; char b = 'b'; if(Character.compare(a, b) > 0) { System.out.println("a is greater"); }else if(Character.compare(a, b) < 0) { System.out.println("a is less than b"); }else System.out.println("Both are equal"); } } |
Output
Using relation operators
We can use relational operators like less than or greater than to compare two characters in Java. It is simplest approach and does not involve any class or method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static void main(String[] args){ char a = 'a'; char b = 'b'; if(a > b) { System.out.println("a is greater"); }else if(a < b) { System.out.println("a is less than b"); }else System.out.println("Both are equal"); } } |
Output
Compare Character objects
You can compare primitive chars either using Character.compare()
method or equals()
method.
Using compare()
You can use compare()
method with Character objects as well. The compare()
method of Characters class returns a numeric value positive, negative or zero.
See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static void main(String[] args){ Character ch1 = 'x'; Character ch2 = 'y'; if(Character.compare(ch1, ch2) > 0) { System.out.println("x is greater"); }else if(Character.compare(ch1, ch2) < 0) { System.out.println("x is less than y"); }else System.out.println("Both are equal"); } } |
Output
Using Equals()
The equals()
method is used to check whether two char objects are equal or not. It returns true
if both are equal else returns false
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Main { public static void main(String[] args){ Character a = 'a'; Character b = 'b'; if(a.equals(b)) { System.out.println("a is equals b"); }else System.out.println("a is not equal to b"); } } |
Output
That’s all about How to compare characters in Java.