How to Compare chars in Java
This tutorial will guide you on how to compare chars in Java.
How to Compare chars in Java?
To compare chars in Java, you can use:
-
- compare() method
- equals() method
- Relational operators
Let’s check out each of them one by one.
How to Compare chars by Using compare() Method?
The “compare()” method of the Java “Character” class numerically compares two characters. This method is used to compare the primitive chars and the Character objects. It takes two characters as parameters to compare and returns a numeric value.
Syntax
The syntax of compare() method is given as:
If both chars “x” and “y” are the same, the compare() method will return “0”. If the first char is less than the second char, it will return a negative value. Similarly, the specified method will return a positive value when the first char is greater than the second char.
Example 1: Compare Primitive chars by Using compare() Method
Let’s compare two primitive characters, “f” and “b”, by using the compare() method. These two characters are stored in “ch1” and “ch2”:
Now, we will use the “compare()” method to compare these two characters with conditional statements:
The output shows that the “ch1” is numerically greater than “ch2”:
Example 2: Compare Character Objects by Using compare() Method
In a Java program, Character objects can also be compared by using the “compare()” method. First, we will create two Character objects “chr1” and “chr2” with “c” and “v” values respectively:
Now, we call the “compare()” method of the Character class to compare these two character objects using the given conditions:

Output
Let’s head towards the second method!How to Compare chars by Using equals() Method?
The “equals()” method also belongs to the “Character” class that can be used to compare the Character objects. It simply compares the values and checks whether these characters are equal or not based on their case.
Syntax
The syntax of the equals() method is as follows:
The “equals()” method takes a character object as a parameter. If the values of the “obj1” and “obj2” are equal, the equals() method returns true; otherwise, it returns false.
Example
In this example, we will compare two Character objects, “k” and “K”, by creating two objects, “ch1” and “ch2” of Character class:
If the value of ch1 is equal to ch2, the equals() method will return true; otherwise it will return false.:
As we know, Java is a case-sensitive language, so the equals() method will return false because “k” and “K” are not equal:
How to Compare chars by Using Relational Operators?
There is one more approach for comparing both primitive characters and Character objects, which is using relational operators such as “==”, “<”, and “>”. These operators can be added in the condition based on the requirements.
The following example will compare two Character objects, “ch1” and “ch2,” using the greater than “>” and less than “<” relational operators.
Example
First, we will create two Character objects, “ch1” and “ch2,” with the following values:
Now, we will use relational operators to compare and check if the ch1 object is greater than or less than the other object:

Output
We have provided all the necessary instructions to compare chars in Java.Conclusion
To compare Character objects in Java, you can use compare() method, and to compare both primitive chars and Character objects, utilize the equals() method and relational operators. Java compares primitive values numerically, whereas the Character objects are compared based on their case or values, depending upon the method you utilize. In this tutorial, we thoroughly discussed methods to compare chars in Java.
About the author

Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.
Класс Character . Обзор методов и констант. Конструктор класса
Класс Character служит оболочкой для типа char . Класс содержит конструктор, который имеет следующую общую форму:
- value – значение, передаваемое в конструктор.
Пример. Приводятся способы инициализации переменной типа Character .
2. Методы класса Character . Обзор
Ниже приводятся основные методы класса Character без перечня методов, поддерживающих кодовые точки в Unicode:
- charValue() – возвращает символ, который помещен в оболочку Character ;
- equals() – сравнить текущий объект с другим объектом типа Character ;
- hashCode() – получить хэш-код объекта;
- compareTo() – сравнить текущий символ с другим символом;
- equals() – сравнить на равенство текущий объект с другим объектом;
- toString() – получить представление символьного значения как тип String ;
- compare() – сравнить два значения типа char ;
- digit() – вернуть числовое значение символа в заданной системе исчисления;
- fordigit() – определить символьное представление числа в заданной системе исчисления;
- isAlphabetic() – определить, является ли символ алфавитным;
- isDefined() – определяет, определен ли символ в кодировке Unicode;
- idDigit() – определяет, есть ли символ цифрой;
- isIdentifierIgnorable() – определяет, нужно ли рассматривать указанный символ как игнорируемый;
- isLowerCase() – определяет, есть ли заданный символ строчной буквой;
- isSpace() – определяет, есть ли заданный символ пробелом на основании кодовой страницы ISO-Latin1;
- isUpperCase() – определяет, является ли заданный символ символом верхнего регистра;
- isWhiteSpace() – определяет, является ли определенный символ пробелом согласно классификации Java;
- reverseBytes() – возвращает значение, получаемое реверсированием порядка байт в заданном значении типа char ;
- valueOf() – возвращает экземпляр типа Character , представляющий определенное значение типа char .
Кроме методов, в классе Character определен ряд следующих констант:
- BYTES – содержит размер типа char в байтах;
- MAX_RADIX – максимальное основание системы исчисления, доступное для преобразования в строку и обратно;
- MAX_VALUE – максимально доступное значение типа char ;
- MIN_VALUE – минимально допустимое значение типа char ;
- SIZE – размер типа в битах;
- TYPE – содержит экземпляр класса типа Class для типа char .
В данной теме рассматриваются базовые методы класса Character . В обзор не включены некоторые методы, которые используют кодовые точки Unicode и переопределяют методы класса Object .
3. Метод charValue() . Получить символ типа char
Метод charValue() возвращает символ примитивного типа char , представленный объектом типа Character . Согласно документации Java общая форма объявления этого метода следующая:
Пример.
4. Метод compareTo() . Сравнить текущий символ с другим символом
Если нужно сравнить текущий символ с некоторым другим символом, то используется метод compareTo() . Синтаксис объявления метода следующий:
здесь anotherCharacter – другой символ, с которым сравнивается символ из текущего экземпляра.
Если символы равны, то функция возвращает 0. Если символ текущего экземпляра меньше символа anotherCharacter , то возвращается значение меньше 0. Термин «меньше» означает, что код символа текущего экземпляра меньше кода символа anotherCharacter . Если код символа текущего экземпляра больше, чем код символа, передаваемый параметром, то функция возвращает значение больше 0.
Фактически, функция возвращает разницу между кодом текущего символа и кодом символа, являющимся входным параметром.Пример.
5. Метод toString() . Получить представление символьного значения как String
Метод toString() переопределяет одноименный метод класса Object . Метод позволяет получить строковое представление символа типа char , хранящегося в текущем экземпляре. Длина результирующей строки равна 1. Общая форма объявления метода следующая
Пример.
6. Константа BYTES . Прочитать размер типа
С помощью константы BYTES можно получить размер в байтах значения типа char, представленного в текущем объекте в беззнаковой (unsigned) двоичной норме.
Согласно документации Java, константа объявляется какПример.
7. Константа MAX_RADIX . Максимальное значение системы исчисления
Константа MAX_RADIX возвращает максимальное значение системы исчисления, доступное для преобразования в строки и наоборот. Согласно документации Java объявления константы имеет вид
Пример.
8. Константа MAX_VALUE . Максимально-допустимое значение типа char
Константа MAX_VALUE имеет объявление
и возвращает максимальное значение типа char , которое равно ‘\uFFFF’ .
Пример.
9. Константа MIN_VALUE . Минимально-допустимое значение типа char
Константа MIN_VALUE возвращает минимально-допустимое значение типа char , которое равно ‘\u0000’ . Объявление константы следующее:
Пример.
10. Константа SIZE . Размер типа в битах
С помощью константы SIZE можно определить размер значения типа char в битах, которое равно 16. Объявление константы следующее
Пример.
11. Константа TYPE . Тип в классе
Тип, инкапсулированный в классе Character , определен в константе TYPE . Эта константа имеет следующее объявление
Пример.
12. Статический метод compare() . Сравнить два значення типа char
Метод compare() статический и используется для сравнения любых двух значений типа char . Сравниваются коды этих значений. Общая форма объявления метода следующая:
Метод возвращает 0, если значения x и y равны.
Метод возвращает значение меньше 0, если x < y . Здесь предполагается сравнение кода символа x с кодом символа y .
Метод возвращает значение больше 0, если x > y . Опять же сравниваются коды символов.
Формула вычисления разницы между x и y следующая:13. Статический метод digit() . Вернуть числовое значение символа в заданной системе исчисления
Статический метод digit() возвращает значение символа типа char в указанной системе исчисления.
Общая форма объявления метода
- ch – символ, который нужно конвертировать в числовое представление;
- radix – система исчисления. Значение radix должно быть в пределах от MIN_RADIX до MAX_RADIX .
Если значение radix выходит за пределы, то функция возвращает –1.
Если значение символа ch не является стойкой цифрой, то функция возвращает -1. Под устойчивой цифрой подразумевается цифра (или буква), входящая во множество цифр заданной системы счисления radix .Например, в 16-й системе исчисления имеется следующее множество цифр: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Если задать ch=’ K’ , то функция вернет –1.
Пример.
14. Статический метод forDigit() . Определить символьное представление числа в заданной системе исчисления
Данный метод позволяет получить символ на основе его числового представления в заданной системе счисления. Метод выполняет обратную функцию по отношению к методу digit() .
Общая форма объявления метода
- digit – целое число, что есть значением в системе счисления radix ;
- radix – система исчисления, в которой конвертируется число digit в результирующий символ
Значение radix должно быть в пределах от MIN_RADIX до MAX_RADIX .
Если число digit не входит во множество символов системы исчисления radix , то возвращается нулевое значение ‘\u0000’ . Такой же возврат из функции, если значение radix некорректно.Пример.
15. Метод reverseBytes() . Реверсировать байты в значении типа char
Статический метод reverseBytes() возвращает входящее значение char , в котором байты представлены в обратном порядке. Согласно документации Java объявление метода следующее
- ch – значение, байты которого нужно представить в обратном порядке.
Пример.
16. Метод valueOf() . Получить экземпляр типа Character
Метод valueOf() возвращает экземпляр типа Character на основе значения типа char . Общий синтаксис объявления метода:
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.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.- Find duplicate characters in String
- Add character to String in java
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.
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.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 .
That’s all about How to compare characters in Java.
Was this post helpful?
Share this
New line character in java
Convert Character to ASCII Numeric Value in Java
Related Posts
Author
Related Posts

Get Unicode Value of Character in Java
Table of ContentsGet Unicode Value of Character in JavaGet Unicode Character Code in Java In this post, we will see how to get unicode value of character in java. Get Unicode Value of Character in Java You can simply use below code to get unicode value of character in java. [crayon-640ea2573e7fc492677931/] Here is complete example […]

Convert Character to ASCII Numeric Value in Java
Learn about how to convert Character to ASCII Numeric Value in Java.

New line character in java
Table of ContentsUsing \n or \r\nUsing Platform independent line breaks (Recommended) In this post, we will see about new line character in java and how to add new line character to a String in different operating systems. Operating systems have different characters to denote the end of the line. Linux and new mac: In Linux, […]

Find Vowels in a String
Table of ContentsFind Vowels in a StringCount number of Vowels in the String In this post, we will see how to find and count vowels in a string. Find Vowels in a String If any character in String satisfy below condition then it is vowel and we will add it to Hashset. character==’a’ || character==’A’ […]

Java remove last character from string
Learn about how to remove last character from String in java using different ways.

Convert char to lowercase java
Table of ContentsMethod signatureParametersReturn type You can use Character class’s toLowerCase method to convert char to lowercase in java. Method signature [crayon-640ea25737f80402984407/] Parameters ch is primitive character type. Return type return type is char. If char is already lowercase then it will return same. [crayon-640ea25737f86972876679/] When you run above program, you will get below output: […]
How to Compare Characters in Java [Practical Examples]
In Java, char is a primitive data type. Whereas, the Character is a wrapper class that is used to wrap a value of the primitive type char in an object. Moreover, an object of Character class contains a single field whose type is char.
There are several ways to compare characters in java as listed below.
- Using Relational Operators
- Using Character.compare()
- Using Character.hashCode()
- Using compareTo() method
- Using equals() method
- Using charValue() method
Using Relational Operators
This is the simplest approach to compare characters in java. Here, we are using relational operators supported in Python to compare the characters in the same way as any numeric value.
Example :
Method-1: Using Character.compare()
In this approach, we are comparing character using compare method of character class. This is a static method that compares two char values numerically. Thereafter, it returns an integer value giving the difference of ASCII value of first parameter by second parameter.
If we compare the character A and B. Then the result will be ASCII(A)-ASCII(B) = 65-66 = -1 .
The syntax of compare function is as shown below. It returns an integer value.Example :
Method-2: Using Character.hashCode()
In this approach, we will compare characters by finding their hashcode which is an ASCII value of that character. The hashcode() method is a static method that returns a hash code for a char type value.
The syntax of hashCode method is as shown below. It returns an equivalent integer value.
Example :
Method-3: Using compareTo()
We can use this approach, if the characters stored in an object of Character class. Here, we will compare characters using compareTo method of Character class. This method returns the result in the same way as compare() method by computing the difference of ASCII value. The only difference between the compare() and the compareTo() method is that compare() method works on primitive type char. Whereas, the compareTo() method works on object of Character class.
The syntax of compareTo method is as shown below. It returns an integer value.
Example :
Method-4: Using equals()
We can use this approach, if the characters are stored in an object of Character class. Here, we will compare characters using equals method of Character class. This method compares current object with the one passed as an parameter for an equality. So, if the character stored in both the object are equal, it will return true, false otherwise.
The syntax of equals() method is as shown below. It returns an integer value.
Example :
Method-5: Using charValue()
We can use this approach, if the characters are stored in an object of Character class. Here, we will extract character from an object using the charValue() method of Character class. Thereafter, we will compare those values using relational operators and result will be a boolean value true or false.
The syntax of charValue function is as shown below. It returns an integer value.
Example :
Compare Characters Examples
Example : Check if the string is palindrome or not
In this example, we are using compare function to compare the characters of the string from both the end.
Example : Check if a character is vowel or consonant
In this example, we are using == relational operator to check for vowels and consonants.
Summary
The knowledge of comparing characters in Java is very useful while working on a real time applications. In this tutorial, we covered six different approaches to compare the characters in java Java. As per the requirement of an application, we can choose an appropriate approach for comparison. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on compare characters in Java.