Compare char with char in java

How to compare chars in Java?

If you are wondering how to compare chars in java, then this article is for you. There are various ways to compare characters in Java language. We can either define the characters using char datatype or we can use Character class. Both are equally good and acceptable.

Compare chars, if defined using char datatype

Defined like this – char firstChar = ‘A’;

a. Using ==

b. Using Character.compare(char1, char2)

There are 3 possible outputs (if provided parameters are characters) –

  • 0 – If both characters are equal.
  • Negative number – If char1 is smaller than char2. For ex – char1 = A and char2 = B.
  • Positive number – If char1 is larger than char2.

c. Using Character.hashCode(char)

You can calculate hasCode for your characters and then compare using if/else conditions.

public class Main < public static void main(String[] args) < char firstChar = 'H'; char secondChar = 'E'; char thirdChar = 'H'; int firstCharHashCode = Character.hashCode(firstChar); int secondCharHashCode = Character.hashCode(secondChar); int thirdCharHashCode = Character.hashCode(thirdChar); System.out.println(firstCharHashCode - secondCharHashCode); // Output: 3 (positive - first char >second char) System.out.println(firstCharHashCode - thirdCharHashCode); // Output: 0 (first char is same as third char) > >

If defined using Character class

Defined like this – Character firstCharObj = new Character(‘A’);

Читайте также:  Питон функции примеры программ

a. Using compareTo()

Its syntax is firstCharObj.compareTo(secondCharObj)

b. Using equals()

This will check if two characters are equal or not.

c. Using getNumericValue()

System.out.println(firstCharNumericVal > secondCharNumericVal); // True | False

d. Using Character.hashCode(charObj)

hashCode() method works with both characters and characters objects.

e. Using charObj.hashCode()

Apart from static method, there is also a public method to call on object directly.

f. Using charObj.charValue()

charValue() returns the character from object. So if your object is –

Character charObj = new Character(‘c’);

then, charObj.charValue() will return c.

Merged Code Example

Live Demo

Источник

Compare Characters in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

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.

4. Conclusion

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.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you'll have results within minutes:

Источник

How to Compare Characters in Java

In this tutorial, I will be sharing how to compare characters in java. Characters can be a char primitive data type or Character wrapper class. Let's dive deep into the topic:

1. Comparing char primitives

1. Using , == operators

Based on the Unicode table, the char primitive data type also has the associated integer value. Using ==, <, >operators you should be able to compare two characters just like you compare two integers.

public class JavaHungry  public static void main(String args[])  char ch1 = 'A'; char ch2 = 'B'; char ch3 = 'A'; System.out.println(ch1==ch2); System.out.println(ch1ch2); System.out.println(ch3==ch1); > > 

Output:
false
true
true

2. Using Character.compare(char x, char y)

We can compare the char values numerically by using compare(char x, char y) method of Character class.

Note: Comparing char primitive values using Character.compare(char x, char y) method returns an integer value.

According to Java docs,
The compare(char a, char b) method of Character class returns the following values:
0, if (a == b)
value less than 0, if a < b
value greater than 0, if a > b

public class JavaHungry  public static void main(String args[])  char ch1 = 'X'; char ch2 = 'Y'; char ch3 = 'X'; System.out.println(Character.compare(ch1,ch2)); System.out.println(Character.compare(ch2,ch3)); System.out.println(Character.compare(ch1,ch3)); > > 

2. Comparing Character objects

You can compare Character class objects:

1. Using Character.compare(char x, char y)

Using Character class constructor, we can convert the char primitive value to the Character object.

public class JavaHungry  public static void main(String args[])  Character ch1 = new Character('X'); Character ch2 = new Character('Y'); Character ch3 = new Character('X'); System.out.println(Character.compare(ch2,ch3)); System.out.println(Character.compare(ch1,ch3)); 
System.out.println(Character.compare(ch1,ch2)); 

Output:
1
0
-1

2. Using equals() method

Using equals() method also we can compare the Character class objects.

public class JavaHungry  public static void main(String args[])  Character ch1 = new Character('X'); Character ch2 = new Character('Y'); Character ch3 = new Character('X'); System.out.println(ch1.equals(ch2)); System.out.println(ch2.equals(ch3)); System.out.println(ch1.equals(ch3)); > > 

Output:
false
false
true

That's all for today, please mention in comments in case you have any questions related to how to compare characters in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Оцените статью