How to Compare Strings in Java


There are a few different ways to compare strings in java, and it can also be quite confusing for a beginner.
This code example aim to show how to compare strings, consider the following code:


package com.javadb.examples;

public class Main {

    public static void main(String[] args) {

        String s1 = new String("abc");
        String s2 = new String("abc");

        if (s1 == s2) {
            System.out.println("s1 == s2");
        }

        if (s1.equals(s2)) {
            System.out.println("s1.equals(s2)");
        }

        if (s1.compareTo(s2) == 0) {
            System.out.println("s1.compareTo(s2) == 0");
        }
    }
}

The output from the above code is:

s1.equals(s2)
s1.compareTo(s2) == 0


The first if statement is never entered since what we are really doing with the == operator is to compare if the string reference is the same for both strings, i.e. both references are pointing to the same string object.
Since we have created two strings using the string constructor (new String()) there are two different string instances existing in memory, and two references pointing to each one.
Had we not used the string constructor, the JVM would have used the same string object for both references, consider this:


        String s1 = "abc";
        String s2 = "abc";

        if (s1 == s2) {
            System.out.println("s1 == s2");
        }


Now the if statement would have been entered since the Java Virtual Machine would use the same string in memory for both s1 and s2 since we are not explicitly telling it to create a new one using the string constructor.
The methods equals() and compareTo() methods of the String class doesn't care if the references are pointing to the same string object or not, they're simply comparing the values.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: