Java how to compare strings

Java how to compare strings

4 ways to compare strings in Java

Since String is a popular data type in Java, the string comparison is probably one of the most commonly used operations. Strings can be compared based on their content as well as their reference.

In this tutorial, we will learn about the following ways to compare two strings with each other:

1. Using Comparison ( == ) Operator

The comparison operator compares two strings by their reference. It does not take into account strings’ values and the only checks the referential equality of two strings. It returns true if both strings refer to the same object, otherwise false.

Look at the above examples. The comparison between 1st and 2nd string returns true because both these variables refer to the same string literal.

On the other hand, when we compare the 2nd string with 3rd string, it returns false. This is because both these strings are pointing to different objects (literal vs object).

Be careful while using comparison ( == ) operator for matching strings. It can potentially lead to unexpected results if you are not sure about the string types.

2. Using equals() method

The equals() method is part of String class inherited from Object class. This method compares two strings based on their contents — character by characters, ignoring their references.

It returns true if both strings have equal length and all characters are in the same order:

Unlike == operator which handles null strings well, calling equals() method from a null string will cause a NullPointerException exception. However, if the string passed to equals() method is null, it returns false.

equalsIgnoreCase() method

If you want to ignore the content case, use equalsIgnoreCase() method instead. This method is similar to equals() but does not consider the casing in characters while comparing strings:

3. Using compareTo() method

The compareTo() method is a part of String class and compares the strings character by character lexicographically and returns an integer value that indicates whether the first string is less than ( 0 value) the second string:

If any of the two strings is null, the compareTo() method throws a NullPointerException exception.

compareToIgnoreCase() method

The compareToIgnoreCase() method is similar to compareTo() method except that it ignores characters case:

4. Using Objects.equals() method

The Objects class is a part of the Java utility package which contains a static equals() method that can be used to compare two strings.

This method returns true if both strings are equal to each other and false otherwise. Consequently, if both strings are null, true is returned and if exactly one string is null, false is returned. Otherwise, equality is determined by using the equals() method of the first string.

Since Objects.equals() internally calls String class’s equals() method, it is case-sensitive.

Bonus: Using Apache Commons

The StringUtils class from Apache Commons Lang library has some very good methods for performing string-related operations. The equals() method of StringUtils class is a null-safe version of the equals() method of String class, which also handles null values.

Before you start using StringUtils utility class methods, make sure that you have added Apache Commons Lang dependency to your project’s pom.xml file:

If you are using Gradle build tool, add the following to your project’s build.gradle file:

Conclusion

That’s folks for comparing strings in Java. We discussed 4 different ways to compare two strings with each other. You should always use Objects.equals() as it is null-safe and performs better.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

What’s the quickest way to compare strings in Java?

What’s the quickest to compare two strings in Java?

Is there something faster than equals?

EDIT: I can not help much to clarify the problem.

I have two String which are sorted alphabetically and EXACTLY the same size

Example: abbcee and abcdee

Strings can be long up to 30 characters

7 Answers 7

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

I don’t expect that Sun Oracle hasn’t already optimized the standard String#equals() to the max. So, I expect it to be already the quickest way. Peek a bit round in its source if you want to learn how they implemented it. Here’s an extract:

Compare Strings of same length faster using the hashcode:

You can test it, my results are for 4000000 compare operations including identical, equal and different strings:

Note: Calculating the hashCode of a new string object takes some computation time and afterwards the hashCode is stored in the object. So my suggested improvement will only be faster than the default compare if string objects are reused. In my application I am using String constants and store strings in collections. Multiple comparisons of strings using my method are actually faster for me, but it may not be in general.

So the fastest way of comparing strings depends on:

How Do I Compare Strings in Java?

Learn more about comparing Strings in Java using the equals to (=) operator.

Join the DZone community and get the full member experience.

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

Learn more about comparing Strings in Java using the equals to (=) operator.

In this article, you are going to learn how to compare strings and the problems that occur when you compare string using equals to ( = )operator.

Introduction

The String is a special class in Java. We use String regularly in Java programs, so comparing two strings is a common practice in Java. In this article, I tried to answer the most common questions about the string, like: «How do I compare strings in Java?»

Comparing strings is very helpful during processes like authentication, sorting, reference matching, etc.

I have listed three different ways to compare strings in Java.

Using equals() method (comparing the content)

Using == operator (comparing the object reference)

Using compareTo() method (comparing strings lexicographically)

1. Compare Strings Using the Equals() Method

equals() method compare two strings for value equality, whether they are logically equal.

equals() method in String class takes another string as a parameter and compares it with the specified string. It returns true if — and only if — the parameter string is not null and contains the same characters as the specified string.

I have asked the program to compare strings using the equals() method below:

2. Compare Strings Using == Operator

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects.

I have given a Java program to compare using == operator below:

Problems Using the == Operator for String Comparison

Most of the beginner Java developers commit this mistake by comparing two strings using the == operator.

Logically, they have to check whether both the string contains the same character sequence or not.

In Java Strings, the == operator is used to check the reference of both the string objects and equals() method used to check the value equality of both strings.

== – checks reference equality

equals() – checks the value equality

When we assign a string value to the string variable, the JVM will check if the string with the equal value already present in the string pool or not. If it is not present in the string pool, it will be added to the constant pool and the reference to that string object is returned.

If it is present in the string pool, the reference to the memory address of that string object is returned.

The following image shows the pictorial explanation of the same.

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

Above, we have » firstString » pointing towards the “coderolls” string in the String pool.

If we are assigning the equal value to another string variable, the JVM checks if the string with that value is present in the string constant pool or not.

Since the string object with that value is already created in the previous step, another string variable starts referring to the previously created string object instance.

The following image shows the pictorial explanation for the ‘ firstString ’ and ‘ secondString ’ pointing towards the “coderolls” string in the string pool.

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

When we create a string using the new operator, a new string object is created and stored in the Java heap space.

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

Above, we can see ‘ firstString ’ and ‘ secondString ’ pointing towards the “ coderolls ” string in the string pool and ‘ thirdString ’ pointing towards the “ coderolls ” in the Java heap space.

It returns a negative integer if the argument string is lexicographically greater than the specified string, i.e. if the argument string follows the specified string. (argument String > specified String )

It returns positive integer if the argument string is lexicographically smaller than the specified string, i.e. if the argument string precedes the specified string. (argument String compareToIgnoreCase() method.

I have given a program for comparing strings using the compareTo() method. It also consists of a case for ignoring the cases with compareToIgnoreCase() method.

Java Compare Strings: A Step-By-Step Guide

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

There are three ways to compare strings in Java. The Java equals() method compares two string objects, the equality operator == compares two strings, and the compareTo() method returns the number difference between two strings.

String comparison is a crucial part of working with strings in Java. For instance, if you’re building an app for a coffee shop that checks who ordered which drink, you may want to compare the name of the customer with the one you have on-file.

This tutorial will discuss, with reference and examples, how to compare strings in Java. We will discuss the three main options used to compare strings, and explore the limitations of the == operator when comparing strings in Java.

By the end of reading this tutorial, you’ll be an expert at comparing strings in Java.

Java Strings

Strings are used for storing text-based data in programming. Strings in Java are defined as a sequence of characters surrounded by double quotation marks. Here’s an example of a string in Java:

But what if we wanted to compare this string with another string? There are three main methods which can be used to compare strings in Java. These are:

Compare Strings Using ==

The == operator, known as the equality operator, is used to compare two strings in Java.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

Suppose we are operating a coffee shop and we want to compare whether a customer’s name matches the one we have associated with a particular order. We could compare these names using the following code:

Our code returns:

Let’s break down our code. First, we declare a class called CompareNames which stores the code for our program. We then declare a variable called orderName which stores the name associated with a particular order, and a variable called customerName which stores the name of the customer who is looking for their drink.

If the values stored within orderName and customerName are equal—which they are in this case—the message The customer’s name matches the order name. is printed to the console. Otherwise, the message The customer’s name does not match the order name. is printed to the console.

Compare String Objects Using ==

In the above example, we declared two strings and used the == operator to compare them. However, this approach does not work when you are comparing two string objects.

Here’s what happens if we try to compare two string objects using the == operator:

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

Find Your Bootcamp Match

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Our code returns:

Even though we assign the string value James to both string objects, the program does not treat them the same. This is because the program will not compare the value of the strings, rather the objects themselves.

Compare Strings Using equals()

The Java string equals() method compares two strings in Java.

Let’s return to the coffee shop example. Suppose we want to compare the name we have associated with a coffee order and the name of a customer. We could do so using this code:

Our code returns:

You can use the equalsIgnoreCase() method in the same way as equals() to compare strings. The only difference between equals() and equalsIgnoreCase() is that the latter compares two strings irrespective of their case, whereas the former is case sensitive.

If you’re interested in learning more about the string equals() method, read our tutorial on the topic.

Compare Strings Using compareTo()

The Java string compareTo() method is used to compare two strings lexicographically.

Java how to compare strings. Смотреть фото Java how to compare strings. Смотреть картинку Java how to compare strings. Картинка про Java how to compare strings. Фото Java how to compare strings

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Find Your Bootcamp Match

The compareTo() method compares the Unicode value of each character in the two strings you are comparing. compareTo() returns 0 if the string is equal to the other string, less than 0 if the string has fewer characters than the other string, and greater than 0 if the string has more characters than the other string.

Suppose we wanted to compare the names of our coffee shop customer and the name we have associated with a drink lexicographically. We could do so using this code:

Our code returns:

In addition, the compareTo() method is case sensitive. If you want to compare strings lexicographically without regard for the cases of the characters in your strings, you can use the compareToIgnoreCase() method. The syntax for the compareTo() and compareToIgnoreCase() method is the same.

Conclusion

Comparing the values stored in two strings is a common operation in Java.

This tutorial discussed how to compare two strings using the equality operator ( == ), the equals() method, and the compareTo() method. We also discussed the limitations of the equality operator in comparing objects. We also walked through an example of each of these methods in action.

You now have the skills you need to start comparing strings in Java like a professional coder!

How to Compare Strings in Java

String is a sequence of characters. It is a data type which is commonly used in Java, thus the comparison of strings is one of the mostly used Java operations. However, very often the developers cannot cope with this operation. If you’re trying to deal with that problem, you’re at the right place! In this article we are going to present different ways to compare strings in Java.

String Comparison with String Class

This method suggests five different ways to compare strings in Java. We are going to take into consideration each of them.

1.1. Using “==” Comparison Operator

Attention: The “==” operator only compares references, not values. So this is an incorrect way to compare text values. Let’s see an example:

Example

As you can see, the two variables point to the same String literal, that’s why the first assertion is true, but the second assertion is false because string1 is created with a literal and string3 is created with the new operator, which means that they reference different objects.

1.2. Using equals()

This method compares two strings based on their content. It’s a comparison by character, which ignores their address. If the two strings are of the same length and the characters are in the same order, it considers them equal and returns true. It returns false if the characters don’t match.

String class suggests two methods

Syntax:

Let’s now see some examples:

Example

In this example, string1, string2, and string4 variables are equal because they have the same case and value irrespective of their address.

For string3 the method returns false, as it’s case sensitive.

Also, if any of the two strings is null, then the method returns false.

Now let’s have a look at another example to make sure you got it.

Example

Here the output will be “Equal”.

1.3. Using equalsIgnoreCase()

As mentioned above, there also exists another method, which returns a boolean value. This method ignores the case of the characters while comparing Strings.

Syntax:

Example

1.4. Using compareTo()

This method compares the characters of two strings lexicographically according to a dictionary or the natural ordering. It returns an integer value that describes if the first string is less than, equal to or greater than the second string.

Let’s imagine string1 and string2 are two different variables. There are three possible scenarios:

It’s high time we saw an example:

Example

1.5. Using compareToIgnoreCase()

This is the same method that the previous one. The only difference is that this method ignores the case.

Example

String Comparison with Objects Class

An utility class Objects contains an equals() method. It can equally be useful to compare two strings.

This method firstly compares the two strings according to their address, and if they are the same, it returns true. If both arguments are null, it returns true, but if one argument is null, it returns false. It’s a case sensitive method because it internally calls the equals() method of the String class.

Let’s check it out with an example.

Example

String Comparison with Apache Commons

The Apache Commons library contains a utility class for string-related operations, which is called String utils and provides useful methods for string comparison. Let’s check them out.

3.1. Using equals() and equalsIgnoreCase()

We have already presented the equals() method of the String class and found out that it doesn’t handle null values. On the contrary, the equals() method of the StringUtils class also accepts null values. So, we can say that this is the upgraded version of the one belonging to the String class.

Example

The equalsIgnoreCase() method of StringUtils returns a boolean value. This works similarly to equals(), except it ignores casing of characters in Strings.

Example

3.2. Using equalsAny() and equalsAnyIgnoreCase()

The first argument of the equalsAny() method is a String and the second one is a multi-args type CharSequence. This method will return true if any of the other Strings given will match against the first String case-sensitively. If not, it will return false.

Now have a look at the following example.

Example

The equalsAnyIgnoreCase() method is the same as the previous one, but in addition to it, this method ignores the casing.

Example

3.3. Using compare() and compareIgnoreCase()

You are already familiar with the compareTo() method of the String class. The compare() method of the StringUtils class is the null-safe version of the previous one, as it handles null values by considering them less than a non-null value. Two null values are considered to be equal.

This method is used to sort a list of Strings with null entries.

Example

The compareIgnoreCase() method is the same, but it also ignores casing.

Example

These are different ways to compare strings in Java. Hope you found it useful.

Источники информации:

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

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