How to compare characters in Java

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.

Let’s take some examples to compare characters in Java.

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.

Output

a is less than b

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.

Output

a is less than b

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.

Output

x is less than y

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.

Output

a is not equal to b

That’s all about How to compare characters in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *