How do I compare strings in Java?

Asked : Nov 17

Viewed : 23 times

I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

Is == bad? When should it and should it not be used? What's the difference?

string java equality 
4 Answers

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

From JLS 3.10.5. String Literals:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Similar examples can also be found in JLS 3.10.5-1.

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

answered Jan 10

Java String compare

We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare String in Java:

  1. By Using equals() Method
  2. By Using == Operator

1) By Using equals() Method

The String class equals() method compares the original content of the string. It compares values of string for equality. String class provides the following two methods:

  • public boolean equals(Object another) compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring the case.

class Teststringcomparison1{  
 	public static void main(String args[]){  
   		String s1="Sachin";  
   		String s2="Sachin";  
   		String s3=new String("Sachin");  
   		String s4="Saurav";  


true true false

In the above code, two strings are compared using equals() method of the String class. And the result is printed as boolean values, true or false.

class Teststringcomparison2{  
 	public static void main(String args[]){  
   		String s1="Sachin";  
   		String s2="SACHIN";  


false true

In the above program, the methods of String class are used. The equals() method returns true if String objects are matching and both strings are of same case. equalsIgnoreCase() returns true regardless of cases of strings.

2) By Using == operator

The == operator compares references not values.

class Teststringcomparison3{  
 	public static void main(String args[]){  
   		String s1="Sachin";  
   		String s2="Sachin";  
   		String s3=new String("Sachin");  
   		System.out.println(s1==s2);//true (because both refer to same instance)  
   		System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  

answered Jan 10

Yea, it's bad...

== means that your two string references are exactly the same object. You may have heard that this is the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some strings are loaded in different ways, constructed from other strings, etc., so you must never assume that two identical strings are stored in the same location.

Equals does the real comparison for you.

answered Jan 10

This post will explore several ways to compare two strings in Java using equals() and compareTo() methods of String class, equals() method of the Objects class, and StringUtils class of Apache Commons library.

1. Avoid equal-to operator (==) method

Every Java programmer should know that equal-to operator == should not be used for string equality as it will check for reference equality, i.e., whether two strings point to the same object or not. This behavior is demonstrated below:

class Main
    public static void main(String[] args)
        String s1 = new String("Equal-to operator in Java");
        String s2 = new String("Equal-to operator in Java");
        System.out.println(s1 == s2);       // Evaluates to false
        System.out.println(null == s2);     // Evaluates to false
        System.out.println(s1 == null);     // Evaluates to false
        System.out.println(null == null);   // Evaluates to true

Since the == operator checks whether the references to the objects are equal or not, it might return true for two string literals with equal value as they will share the same object in the JVM string pool, as shown below. It is recommended not to rely on such behavior and use standard methods for string equality.

class Main
    public static void main(String[] args)
        String s1 = new String("Equal-to operator in Java");
        String s2 = new String("Equal-to operator in Java");
        // Evaluates to true as both objects point to the same reference
        // in String pool
        System.out.println(s1 == s2);

2. Using String.equals() method

Java String class has the equals() method that compares the actual contents of a string with another string and returns a boolean value determining if they are the same or not. The String class also offers:

  1. equalsIgnoreCase(String) method, which is similar to the equals() method except it ignores the case of characters in the String.
  2. contentEquals(CharSequence) method, which compares the string to the specified CharSequence.
  3. contentEquals(StringBuffer) method, which compares the string to the specified stringBuffer.

Here’s a simple Java program that demonstrates the working of the equals() method. Note that we should not call equals() on an empty string as it will lead to a NullPointerException.

class Main
    public static void main(String[] args)
        String s1 = new String("Compare two strings in Java");
        String s2 = new String("Compare two strings in Java");
        System.out.println(s1 != null && s1.equals(s2));    // Evaluates to true

answered Jan 10

Login and Submit Your Answer
Browse other questions tagged  string  java  equality or ask your own question.