Check if Strings are equal in Java

Sign up for FREE 1 month of Kindle and read all our books for free.

Get FREE domain for 1st year and build your brand new site

In this article, we have explored how to find if two strings are equal in Java. There are three ways to check if two strings in Java are equal:

  • By == operator
  • By equals() method
  • By compareTo() method

Before going into this, we will get basic idea of strings in Java.

Like we use integer and floating point data type in programming, String is a data type used to represent the text. It is comprised of set of characters or in java it is an object which represents a sequence of characters which could have spaces as well as numbers.

String must be enclosed in quotations marks i.e in "" to make data recognized as a string.

for example:

"Open", "Genus" these are two different strings.

As string could contain spaces, a sentence is also a string.

for example:

"OpenGenus is an open-source organization" is a string.

As string could contain numbers.

for example:

"n comes 2 times in word OpenGenus","Open1" and "5678" are also strings.

Strings are immutable. It means strings are constant object whose value cannot be changed or modified after once created.

Creation and storage of String

The way string is being stored depends on the way string has been created.
Whenever the memory is allocated to a java program, JVM divides the memory in to two parts-

1.stack- used for execution purpose.

2.heap- used for storage purpose.
So at the time of allocation JVM allocates some part of heap memory specially for string literals called String Constant Pool.

There are two ways to create a string-

1. By using String literal

In java string literal is created by using double quotes.

for example

String s1 = "Genus";

Here compiler will create the string object having string literal "Genus" and will assign it to the string instance s1.
These type of string objects are stored in String Constant Pool.
JVM first checks the content of the object to be created. If the object with same value already exist in the pool then it does not create a new object and rather, it assigns the reference of the same existing object to new instance. It means there can never be two objects in the pool having same content or value.

For example:

String s1 = "Genus";
String s2 = "Genus";
String s3 = "Genus";

These are three string instances that have same value "Genus", then it means that in pool space there is only one object suppose let it be s1 having the value "Genus" then all remaining string instances i.e s2 and s3 are pointing to s1.

But, what if we want to have two different string objects having same values?

So, the answer of your all doubts is below.

2. By using new Keyword

In java a new string object is created using a new keyword independent of whether the object with same value exist or not.
for example-

String s4 = new String("Genus");
String s5 = new String("Genus");

Here compiler would create two different string objects s4 and s5 in the memory each having the value "Genus".
These type of string objects are stored in the heap memory.

String Equality

There are three ways to check the equality of two strings in java.

It depends on which basis they are being compared i.e on the basis of value or reference.

1. By == operator

The == operator compares two string objects on the basis of their reference for equality i.e It returns true if two objects being compared have same physical address in the memory otherwise it will return false.

As we have learnt that if the strings created using string literal have same value then they have same address as well as both instance refers to same object then in that case == operator will return true and in case when new string is created using new keyword then new object would be created in nonpool then it will return false even after having the same value as it will have different address in the memory.

for example-

class CheckEquality1 {
    public static void main(String args[]) {
        String s1 = "Genus";
        String s2 = "Genus";
        String s3 = new String("Genus");
        String s4 = new String("Genus");
        System.out.println(s1==s2);//true(as both refers to same instance i.e created in pool space)
        System.out.println(s1==s3);//false(as s3 refers to the object created in nonpool)
        System.out.println(s4==s3);//false(as both refers to different addresses)

2. By equals() method

The equals() method compare two strings on the basis of their values or content for equality.

There are two methods provided by String class in java:

i) String.equalsIgnoreCase()

This method compare the strings ignoring the case(case-insensitive). It returns true if values of both the strings is same ignoring the case, else return false.

ii) String.equals()

This method compare the strings considering the case(case-sensitive), if the value or content of both strings is same considering the case then return true else return false.

class CheckEquality2 {
    public static void main(String args[]) {
        String s1 = "Genus";
        String s2 = new String("Genus");
        String s3 = new String("genus");
        System.out.println(s1.equals(s2));//true(as both have same values)
        System.out.println(s1.equals(s3));//false(char mismatch as 'G' is not equal to 'g')
        System.out.println(s2.equals(s3));//false(char mismatch as 'G' is not equal to 'g')
        System.out.println(s1.equalsIgnoreCase(s3));//true(as case is ignored)
        System.out.println(s2.equalsIgnoreCase(s3));//true(as case is ignored)

3. By compareTo() method

The compareTo() method compare two strings lexicographically and returns 0 if strings are equal else positive or negative value depending upon if the first string is lexicographically larger or smaller respectively.

Suppose s1 and s2 are two strings.

if :
s1 == s2 : 0
s1 > s2  : positive
s1 < s2  : negative

Each character of both the strings is converted into a Unicode value for comparison.

The value is calculated as (int)s1.charAt(i)-(int)s2.charAt(i).
where i is an index for strings.

class CheckEquality3 {
    public static void main(String args[]) {
        String s1 = "Genus";
        String s2 = "Genus";
        String s3 = "Genius";
        System.out.println(s1.compareTo(s2));// 0 (as s1=s2)
        System.out.println(s1.compareTo(s3));// 12(as s1>s3)
        System.out.println(s3.compareTo(s1));// -12(as s3>s1)

With this article at OpenGenus, you must have the complete idea of checking if Strings are equal in Java.