How to compare two strings in Java 8

In this post, we will see how to compare two String in java.
As you might know, String implements Comparable interface, you can use compareTo method to compare two String in java.

import java.util.Scanner;

public class StringComparator

   public static void main(String args[])

      Scanner scan = new Scanner(System.in);

      System.out.print("Enter First String : ");

      System.out.print("Enter Second String : ");

      if(str1.compareTo(str2) > 0){

         System.out.println("First String is Greater than Second String.");

      }else if(str1.compareTo(str2) < 0){

         System.out.println("First String is Smaller than Second String.");

         System.out.println("Both Strings are Equal (i.e. String1 is Equal to String2)");

Output:

Enter First String : JavaEnter Second String : Blog

First String is Greater than Second String.

That’s all about How to compare two Strings in java.

Let us know if you liked the post. That’s the only way we can improve.

How to compare two strings in Java 8

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.

You may also like: The Do's and Don'ts of Java Strings

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.

  1. Using equals() method (comparing the content)

  2. Using == operator (comparing the object reference)

  3. Using compareTo() method (comparing strings lexicographically)

1. Compare Strings Using the Equals() Method

In this way, I am using .equals() instance method of the String class. Originally .equals() method is the Object class method, String class overrides it.

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:

Output:


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.

When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false.

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

Output:


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.

How to compare two strings in Java 8

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.

How to compare two strings in Java 8


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

How to compare two strings in Java 8

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 < specified String )

It returns zero if both the strings are lexicographical equals. (argument String = specified String )

If you want to ignore the cases of both the string use 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.

Output:

I have written a detailed article on how to compare strings lexicographically in Java if you want to learn more.

Conclusion

We can compare strings using the ways given below:

  1. Using equals() method: equals() method in the strings used to check the string value equality whether they contain the same character sequence.
  2. Using == operator: == operator used to check the reference equality of the two strings, whether they are pointing towards the same string object.
  3. Using compareTo() method: compareTo() method used to check the strings lexicographically, i.e. alphabetically. Check the detailed articles on how to compare strings lexicographically.

Most of the beginner Java developers make mistakes while comparing strings. They want to check the content of the string, but they use the == operator to check it.

It is always advised to use equals() method to compare the string based on its content.

If you have any queries about the code blocks given above, please write it down in the comment section below. Also, let me know if you have any other way to compare two strings in Java in the comment section.

This article originally published at coderolls.com/compare-strings-in-java.

Further Reading

The Do's and Don'ts of Java Strings

Java Strings Tutorials: Becoming a Java Strings Virtuoso