Как сравнить два char в java
Перейти к содержимому

Как сравнить два char в java

  • автор:

Как сравнить char в java

Аватар пользователя Иван Полежаев

Для сравнения символов в Java можно использовать оператор сравнения == Например:

Также можно использовать метод equals класса Character :

Обратите внимание, что если необходимо сравнить символы, которые хранятся в строках, то нужно использовать метод charAt класса String :

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

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-64f6f3a2a87e4742927760/] Here is complete example […]

Convert chartacter to ascii in java

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-64f6f3a2a9508636230134/] Parameters ch is primitive character type. Return type return type is char. If char is already lowercase then it will return same. [crayon-64f6f3a2a950d632746994/] When you run above program, you will get below output: […]

How to Compare Character in Java

This article explains different methods and examples for how to compare characters in java. A variety of built-in Java methods can be used to compare characters in java, such as the compare() and equals() methods. It is possible to compare primitive characters as well as Character objects. The following is a detailed explanation of how to compare characters in java.

Introduction

The Java programming language provides methods for comparing characters, including compare() and equals() . We can compare primitive characters and Character objects. Let's look at these methods in more detail and explore how to compare characters in java. Although we can use the less than and greater than operators, they are only useful for primitive values. The compare(char x, char y) method of the Character class compares two char values numerically in a similar way to the following:

How to Compare Primitive Characters?

a. Using the Character.compare()

In this method, characters are compared using the comparison method of the character classes in this approach. Using this method, you can compare two char values numerically. Afterward, it returns an integer value corresponding to the difference between the ASCII values of the first and second parameters

Example:

In this example we have used the Character.compare() method to compare the characters.

Output:

Code Explanation:

In the above example we have initialized two characters C and D and compared them using Character.compare() . Since the ASCII value of c is less than d we get the output as c is lesser than d

b. Using Relational Operators

In Java, we can compare characters by using relational operators such as < , > , or = . It is possible to compare only primitive characters with this method. In the example below, two characters are compared using relational operators in Java. There are no classes or methods involved in this method, making it the simplest.

Example:

In this example, we have used the relational operator's method to compare the characters.

Output:

Code Explanation:

In the above example, we have initialized two characters E and F and compared them using relational operators. Since the ASCII value of c is less than d we get the output as c is lesser than d

c. Using the Character.hashCode()

This approach compares characters by determining their hashcode, which is their ASCII value. The hashcode() static method returns the hash code of a char value.

Example:

In this example, we have used the Character.hashCode() method to compare the characters.

Output:

Code Explanation:

In the above example, we have initialized two hashcodes @ and # , and compared them using Character.hashCode() . Since the ASCII value of @ is greater than # we get the output as c is lesser than d

How to Compare Character Objects?

a. Using compare()

A compare() method builds a comparison between two class-specific objects (x, y) with parameters. It returns the following values:

  • 0 : if (a == b)
  • -1 : if (a < b)
  • 1 : if (a > b)

Example:

In this example we have used the compare() method to compare the character objects.

Output:

Code Explanation:

In the above example, we have assigned values of a and b and have used the compare() method to check whether they are equal or not. And depending on the result we return 0 (or) 1

b. Using Character.compareTo() method

By calling the compareTo() method on the Java class, an object can be lexicographically compared with the current object. Depending on the value, it will return a positive or negative number. Strings are compared based on their Unicode values.

The first object returns a positive number if it is lexicographically greater than the second object. A negative number is returned if the first object is lexicographically less than the second object, and a zero value is returned if the first object is lexicographically equal to the second object.

Example:

In this example, we have used the Character.compareTo() method to compare the character objects.

Output:

Code Explanation:

In the above example, we have assigned values of a , x , and w and have used Character.compareTo() method to check whether they are equal or not. And depending on the result we return 0 , 1 , (or) -1

c. Using charValue()

When characters are stored in an object of the Character class, we can use this approach. Using the Character class's charValue() method, we will extract character values from an object. A value that is greater than a , greater than b , or equal to both will be returned when we compare those values with relational operators.

Example

In this example, we have used the charVaue() method to compare the character objects.

Output:

Code Explanation:

In the above example, we have assigned values of a and b and have used Character.charValue() method to check whether they are equal or not. And depending on the result we return true (or) false

d. Using Objects.equals() method

It is possible to apply this approach if the characters are stored in an object of the Character class. The equals method of the Character class compares the current object to the parameter passed as a parameter for equality. In other words, if both objects contain the same character, it returns true , otherwise false .

Example:

In this example, we have used the Object.equals method to compare the character objects.

Output:

Code Explanation:

In the above example we have assigned values of a and b and have used Object.equals() method to check whether they are equal or not. And depending on the result we return true (or) false

Some Examples of How to Compare Characters in Java

a. Check if the string is palindrome or not

We use compare function in this example to compare the characters of the string from both ends.

Output:

Code Explanation:

In the above example, we have used the compare() function to check whether a given string is palindrome or not

b. Check if a character is a vowel or consonant

This example uses the == operator and the || operator to search for vowels and consonants.

Output:

Code Explanation:

In the above example, we have used the relational operators to search for vowels and consonants. Depending upon the input of the user we print it either as a vowel or a consonant

Comparing chars in Java

I want to check a char variable is one of 21 specific chars, what is the shortest way I can do this?

Doesn’t seem to be working. Do I need to write it like:

13 Answers 13

If your input is a character and the characters you are checking against are mostly consecutive you could try this:

However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:

If you have a character you’ll first need to convert it to a string before you can use a regular expression:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *