DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples
  • Proper Java Exception Handling
  • Generics in Java and Their Implementation

Trending

  • The Future of Kubernetes: Potential Improvements Through Generative AI
  • The Data Streaming Landscape 2024
  • 10 Tips To Improve Python Coding Skills in 2024
  • Implementing Persistence With Clean Architecture
  1. DZone
  2. Data Engineering
  3. Data
  4. How Do I Compare Strings in Java?

How Do I Compare Strings in Java?

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

By 
Gaurav Kukade user avatar
Gaurav Kukade
·
Updated Jan. 31, 20 · Analysis
Like (14)
Save
Tweet
Share
205.2K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Java
 




x
14


 
1
public boolean equals(Object anObject)
2

          
3
It compare this string with the argument strings and return true if the argument is not null and contains the same character as the specified string.
4

          
5
param -
6
another string
7

          
8
returns -
9

          
10
true - if argument is not null and it contains same characters as the specified string
11
false - if the argument is null or it does not contain same characters as the specified string
12

          
13
ex. firstString.equals(secondString)
14
// returns true if and only if the secondString is not null and contains the same characters as firstString.



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

Java
 




xxxxxxxxxx
1
33


 
1
/**
2
 * A Java program to compare two strings using equsls()
3
 * and equalsIgnoreCase() method of the String.
4
 * 
5
 * @author Gaurav Kukade at coderolls.com
6
 */
7

          
8
public class CompareUsingEquals {
9

          
10
  public static void main(String[] args) {
11
    String firstString = "coderolls";
12
    String secondString = "javablog";
13
    String thirdString = "coderolls";
14
    String fourthString = "CodeRolls";
15

          
16
    System.out.println("Comparing strings using equals() and equalsIgnoreCase() method\n");
17

          
18
    // Using equals() method
19
    System.out.print("firstString.equals(secondString) : ");
20
    System.out.println(firstString.equals(secondString));
21

          
22
    System.out.print("firstString.equals(thirdString) : ");
23
    System.out.println(firstString.equals(thirdString));
24

          
25
    /*
26
     * Using equalsIgnoreCase() method to ignore
27
     * case consideration (i.e. Capital or small) of both the strings.
28
     */
29
    System.out.print("firstString.equalsIgnoreCase(fourthString) : ");
30
    System.out.println(firstString.equalsIgnoreCase(fourthString));
31
  }
32

          
33
}



Output:

Java
 




xxxxxxxxxx
1


 
1
Comparing strings using equals() and equalsIgnoreCase() method
2

          
3
firstString.equals(secondString) : false
4
firstString.equals(thirdString) : true
5
firstString.equalsIgnoreCase(fourthString) : true



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:

Java
 




x
43


 
1
/**
2
 * A Java program to compare strings using == operator.
3
 * 
4
 * == operator ckecks whether both the strings referring
5
 * to the same String Object.
6
 * 
7
 * @author Gaurav Kukade at coderolls.com
8
 */
9
10
public class CompareUsingEqualsToOperator {
11
12
  public static void main(String[] args) {
13
14
    String firstString = "coderolls";
15
    String secondString = "javablog";
16
    String thirdString = "coderolls";
17
18
    // creating new String object with the same value as firstString or thirdString
19
    String fourthString =  new String("coderolls");
20
21
    System.out.println("Comparing strings using == operator \n");
22
23
    System.out.print("firstString == secondString : ");
24
    System.out.println(firstString == secondString);
25
26
    /*
27
     * Here firstString and thirdString is referring to the same String object
28
     * hence it will print 'true'.
29
     */
30
    System.out.print("firstString == thirdString : ");
31
    System.out.println(firstString == thirdString);
32
33
    /*
34
     * Here firstString and fourthString have same value
35
     * but they are referring to the different String object.
36
     * 
37
     * hence it will print 'false'
38
     */
39
    System.out.print("firstString == fourthString : ");
40
    System.out.println(firstString == fourthString);
41
  }
42
43
}



Output:

Java
 




xxxxxxxxxx
1


 
1
Comparing strings using == operator 
2

          
3
firstString == secondString : false
4
firstString == thirdString : true
5
firstString == fourthString : false



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.

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.


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

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.

Java
 




xxxxxxxxxx
1
36


 
1
/**
2
 * A Java program to compare strings using compareTo()
3
 * and compareToIgnoreCase() method.
4
 * 
5
 * compareTo() compare strings lexicograpgically.
6
 * 
7
 * @author Gaurav Kukade at coderolls.com
8
 */
9

           
10
public class CompareUsingCompareTo {
11

           
12
  public static void main(String[] args) {
13
    
14
    String firstString = "java";
15
    String secondString = "coderolls";
16
    String thirdString = "sql";
17
    String fourthString = "CodeRolls";
18
    
19
    System.out.println("Comparing strings using compareTo() and compareToIgnoreCase() method\n");
20
    
21
    // Using compareTo() method
22
    System.out.print("firstString.compareTo(secondString) : ");
23
    System.out.println(firstString.compareTo(secondString));
24
    
25
    System.out.print("firstString.compareTo(thirdString) : ");
26
    System.out.println(firstString.compareTo(thirdString));
27
    
28
    /*
29
     * Using compareToIgnoreCase() method to ignore
30
     * case consideration (i.e. Capital or small) of both the strings.
31
     */
32
    System.out.print("secondString.compareToIgnoreCase(fourthString) : ");
33
    System.out.println(secondString.compareToIgnoreCase(fourthString));
34
  }
35

           
36
}



Output:

Java
 




xxxxxxxxxx
1


 
1
Comparing strings using compareTo() and compareToIgnoreCase() method
2

          
3
firstString.compareTo(secondString) : 7
4
firstString.compareTo(thirdString) : -9
5
secondString.compareToIgnoreCase(fourthString) : 0



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


Strings Java (programming language) Data Types

Published at DZone with permission of Gaurav Kukade. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples
  • Proper Java Exception Handling
  • Generics in Java and Their Implementation

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: