In this short tutorial, we'll explore different ways to compare characters in Java.
We'll start by discussing how to compare primitive characters. Then, we'll look at different methods of comparing Character objects.
2. Comparing Primitive Characters
Firstly, let's begin by highlighting how to compare primitive characters.
2.1. Using Relational Operators
Typically, the simplest way to compare characters is using the relational operators.
In short, characters are compared in Java depending on the order of their ASCII code:
assertFalse('a' == 'A'); assertTrue('a' < 'v'); assertTrue('F' > 'D');
2.2. Using Character.compare() Method
Similarly, another solution would be using the compare() method of the Character class.
Simply put, the Character class wraps a value of the primitive type char in an object. The compare() method accepts two char parameters and compares them numerically:
assertTrue(Character.compare('C', 'C') == 0); assertTrue(Character.compare('f', 'A') > 0); assertTrue(Character.compare('Y', 'z') < 0);
As shown above, the compare(char a, char b) method returns an int value. It denotes the difference between the ASCII code of a and b.
The returned value is equal to zero if the two char values are identical, less than zero if a < b, and greater than zero otherwise.
3. Comparing Character Objects
Now that we know how to compare primitive characters, let's see how to compare Character objects.
3.1. Using Character.compareTo() Method
The Character class provides the compareTo() method to compare two character objects numerically:
Character chK = Character.valueOf('K'); assertTrue(chK.compareTo(chK) == 0); Character chG = Character.valueOf('G'); assertTrue(chK.compareTo(chG) > 0); Character chH = Character.valueOf('H'); assertTrue(chG.compareTo(chH) < 0);
Here, we used the valueOf() method to create Character objects since the constructor is deprecated since Java 9.
3.2. Using Object.equals() Method
Moreover, one of the common solutions to compare objects is using the equals() method. It returns true if the two objects are equal, false otherwise.
So, let's see how we can use it to compare characters:
Character chL = 'L'; assertTrue(chL.equals(chL)); Character chV = 'V'; assertFalse(chL.equals(chV));
3.3. Using Objects.equals() Method
The Objects class consists of utility methods for operating on objects. It offers another way to compare character objects through the equals() method:
Character chA = 'A'; Character chB = 'B'; assertTrue(Objects.equals(chA, chA)); assertFalse(Objects.equals(chA, chB));
The equals() method returns true if the character objects are equal to each other and false otherwise.
In this article, we learned a variety of ways to compare primitive and object characters in Java.
As always, the code used in this article can be found over on GitHub.