zeroTutorials

Java, Server, Database Tutorials

Have a Question?

If you have any question you can ask below or enter what you are looking for!

Compare strings in Java

In order to compare the values of two strings, we use the equals() method or Objects.equals() method. Objects.equals() checks for null before calling equals() method.

While the == operator is used to compare the references of two string objects.

import java.util.Objects;

public class CompareStrings {

    public static void main(String[] args) {

        // 1. Compare two strings with the same value using the equals() method.
        boolean compareByValue1 = new String("hello").equals("hello");
        System.out.println("compareByValue1 : " + compareByValue1);

        // 2. Compare two strings with the same value using the Objects.equals() method.
        boolean compareByValue2 = Objects.equals(new String("hello"), "hello");
        System.out.println("compareByValue2 : " + compareByValue2);

        // 3. Compare the references of two string objects.
        boolean compareByReference = new String("hello") == "hello";
        System.out.println("compareByReference : " + compareByReference);

    }
}

Output :

compareByValue1 : true
compareByValue2 : true
compareByReference : false
Tags:  ,