Compare two Strings in Java

Compare two Strings in Java

Last Updated : 22 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The string is a sequence of characters. In Java, objects of String are immutable which means they are constant and cannot be changed once created. 

Methods to Compare Strings in Java

Below are 5 ways to compare two Strings in Java:

  1. Using user-defined function
  2. Using String.equals()
  3. Using String.equalsIgnoreCase()
  4. Using Objects.equals()
  5. Using String.compareTo()

1. Using user-defined function: 

Define a function to compare values with the following conditions :

  1. if (string1 > string2) it returns a positive value.
  2. if both the strings are equal lexicographically i.e.(string1 == string2) it returns 0.
  3. if (string1 < string2) it returns a negative value.

2. Using String.equals() :

In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false. 

Syntax:

str1.equals(str2);

Here str1 and str2 both are the strings that are to be compared. 

Examples:

Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: false

Program: 

Java
// Java program to Compare two strings
// lexicographically
public class GFG {
    public static void main(String args[])
    {
        String string1 = new String("Geeksforgeeks");
        String string2 = new String("Practice");
        String string3 = new String("Geeks");
        String string4 = new String("Geeks");
        String string5 = new String("geeks");

        // Comparing for String 1 != String 2
        System.out.println("Comparing " + string1 + " and "
                           + string2 + " : "
                           + string1.equals(string2));

        // Comparing for String 3 = String 4
        System.out.println("Comparing " + string3 + " and "
                           + string4 + " : "
                           + string3.equals(string4));

        // Comparing for String 4 != String 5
        System.out.println("Comparing " + string4 + " and "
                           + string5 + " : "
                           + string4.equals(string5));

        // Comparing for String 1 != String 4
        System.out.println("Comparing " + string1 + " and "
                           + string4 + " : "
                           + string1.equals(string4));
    }
}

Output
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : false
Comparing Geeksforgeeks and Geeks : false



3. Using String.equalsIgnoreCase() : 

The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false. Syntax:

str2.equalsIgnoreCase(str1);

Here str1 and str2 both are the strings which are to be compared. 

Examples:

Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: true

Program: 

Java
// Java program to Compare two strings
// lexicographically
public class GFG {
    public static void main(String args[])
    {
        String string1 = new String("Geeksforgeeks");
        String string2 = new String("Practice");
        String string3 = new String("Geeks");
        String string4 = new String("Geeks");
        String string5 = new String("geeks");

        // Comparing for String 1 != String 2
        System.out.println(
            "Comparing " + string1 + " and " + string2
            + " : " + string1.equalsIgnoreCase(string2));

        // Comparing for String 3 = String 4
        System.out.println(
            "Comparing " + string3 + " and " + string4
            + " : " + string3.equalsIgnoreCase(string4));

        // Comparing for String 4 = String 5
        System.out.println(
            "Comparing " + string4 + " and " + string5
            + " : " + string4.equalsIgnoreCase(string5));

        // Comparing for String 1 != String 4
        System.out.println(
            "Comparing " + string1 + " and " + string4
            + " : " + string1.equalsIgnoreCase(string4));
    }
}

Output
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : true
Comparing Geeksforgeeks and Geeks : false



4. Using Objects.equals() : 

Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument. Syntax:

public static boolean equals(Object a, Object b)

Here a and b both are the string objects which are to be compared. 

Examples:

Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: null
Input 2: null
Output: true

Program: 

Java
// Java program to Compare two strings
// lexicographically

import java.util.*;

public class GFG {
    public static void main(String args[])
    {
        String string1 = new String("Geeksforgeeks");
        String string2 = new String("Geeks");
        String string3 = new String("Geeks");
        String string4 = null;
        String string5 = null;

        // Comparing for String 1 != String 2
        System.out.println(
            "Comparing " + string1 + " and " + string2
            + " : " + Objects.equals(string1, string2));

        // Comparing for String 2 = String 3
        System.out.println(
            "Comparing " + string2 + " and " + string3
            + " : " + Objects.equals(string2, string3));

        // Comparing for String 1 != String 4
        System.out.println(
            "Comparing " + string1 + " and " + string4
            + " : " + Objects.equals(string1, string4));

        // Comparing for String 4 = String 5
        System.out.println(
            "Comparing " + string4 + " and " + string5
            + " : " + Objects.equals(string4, string5));
    }
}

Output
Comparing Geeksforgeeks and Geeks : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and null : false
Comparing null and null : true



5. Using String.compareTo() for Comparing Two Strings

Syntax of String compareTo()

int str1.compareTo(String str2)

Working: It compares and returns the following values as follows:

  1. if (string1 > string2) it returns a positive value.
  2. if both the strings are equal lexicographically i.e.(string1 == string2) it returns 0.
  3. if (string1 < string2) it returns a negative value.

Below is the implementation of the above method

Java
// Java program to Compare two strings
// Using String.compareTo() 

import java.util.*;

// Diver Class
public class GFG {
    public static void check(String string1, String string2)
    {
        if (string1.compareTo(string2)!=0) {
            System.out.println(string1 + " " + string2
                               + " : Not Equal");
        }
        else {
            System.out.println(string1 + " " + string2
                               + " : Equal");
        }
    }

    // main function
    public static void main(String args[])
    {
        String string1 = new String("Geeksforgeeks");
        String string2 = new String("Geeks");
        String string3 = new String("Geeks");
        String string4 = " ";
        String string5 = " ";

        // Comparing for String 1 != String 2
        check(string1, string2);

        // Comparing for String 2 = String 3
        check(string2, string3);

        // Comparing for String 1 != String 4
        check(string1, string4);

        // Comparing for String 4 = String 5
        check(string4, string5);
    }
}

Output
Geeksforgeeks Geeks : Not Equal
Geeks Geeks : Equal
Geeksforgeeks   : Not Equal
    : Equal



Note: NULL string can’t be passed as a argument to compareTo() method.

To know more about the topic refer to the String.compareTo() article. 

Why not use == for the comparison of Strings?

In general, both equals() and “==” operators in Java are used to compare objects to check equality but here are some of the differences between the two:

  1. The main difference between the .equals() method and == operator is that one is the method and the other is the operator.
  2. One can use == operators for reference comparison (address comparison) and the .equals() method for content comparison.
    • Both s1 and s2 refer to different objects.
    • When one uses == operator for the s1 and s2 comparison then the result is false as both have different addresses in memory.
    • Using equals, the result is true because it’s only comparing the values given in s1 and s2.

To know more about the topic refer to the comparison of strings article.



Previous Article
Next Article

Similar Reads

Compare two strings lexicographically in Java
In this article, we will discuss how we can compare two strings lexicographically in Java. One solution is to use Java compareTo() method. The method compareTo() is used for comparing two strings lexicographically in Java. Each character of both the strings is converted into a Unicode value for comparison. int compareTo(String str) :It returns the
3 min read
How to Initialize and Compare Strings in Java?
As we all know String is immutable in java so do it gives birth to two ways of initialization as we do have the concept of String Pool in java. Ways: Initializing Strings in Java Direct initializationIndirect initialization Way 1: Direct Initialization(String Constant) In this method, a String constant object will be created in String pooled area w
4 min read
How to Compare two Collections in Java?
Java Collection provides an architecture to store and manipulate the group of objects. Here we will see how to compare Elements in a Collection in Java. Steps: Take both inputs with help of asList() function.Sort them using Collections.sort() method.Compare them using equals() function.Print output. (true means both are equal and false means both a
2 min read
Java Program to Compare Two Objects
An object is an instance of a class that has its state and behavior. In java, being object-oriented, it is always dynamically created and automatically destroyed by the garbage collector as the scope of the object is over. Illustration: An example to illustrate an object of a class: Furniture chair=new Furniture(); Furniture sofa=new Furniture(); /
7 min read
Java Program to Compare two Boolean Arrays
Two arrays are equal if they contain the same elements in the same order. In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is .equals() method.By using the Naive approach. Examples: Input : A = [true , true , false] A1 = [true, true, false] Output: Both the arrays are equal. Input : A = [true, true, false] A1
3 min read
Java Program to Compare two Double Arrays
Java double array is used to store double data type values only. The default value of the elements in a double array is 0. We can compare two double arrays by two ways: By naive approach of traversing through the whole array and comparing each element.By Arrays.equals() method. Method 1: Naive Approach By Comparing one element at a time by traversi
2 min read
Java Program to Compare two Float Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.The base value is index 0 and the difference between the two indexes is the offset. In this program, we need to compare two arrays having elements of float type. Two arrays are equal if they contain the same element
3 min read
How to Compare Two TreeMap Objects in Java?
TreeMap class in java provides a way of storing key-value pairs in sorted order. The below example shows how to compare two TreeMap objects using the equals() method. It compares two TreeMap objects and returns true if both of the maps have the same mappings else returns false. Syntax: boolean equals(Object o) Return: It returns true if both the ma
1 min read
Compare Two HashMap Objects in Java
In this article, we will learn how to compare two HashMap objects in Java. In java.util package HashMap class is present. HashMap is used to store key-value pairs, so there are different scenarios to compare two Objects of HashMap. Which is the following: Compare EntryCompare KeysCompare ValuesExample: Input : HashMapA = [a=1, b=2], HashMapB = [a=1
4 min read
equals() and deepEquals() Method to Compare two Arrays in Java
Arrays. equals() method does not compare recursively if an array contains another array on other hand Arrays. deepEquals() method compare recursively if an array contains another array. Arrays.equals(Object[], Object[]) Syntax : public static boolean equals(int[] a, int[] a2) Parameters : a - one array to be tested for equalitya2 - the other array
3 min read
Practice Tags :