How to compare strings in Java

Introduction

 
There are two ways to compare strings in Java
  • "==" operator
    [Compares references not values]
  • ".equals()" method, derived from object class, i.e. java.lang.object.equals()
    [Compares values for equality]
 
Note: .equals() method is automatically defined for each and every class, because it is defined in Object class, from which all other classes are derived.
 
In the case of String, Most of the programmers are gone in the wrong way, i.e. using "==" operator to compare equality of Strings. String is a Java Type, it just defines an object. String is not an array of characters in java.
 
Syntax to define an object of String type:
 
String str = "This is a string object."
  
where str is an object of String type.
 
The right way of comparing equality of two Strings: use ".equals()" method instead of "==" operator.
 
The following program demonstrates the above statement
 

== versus .equals()

 
Code:
  1. public class JavaApplication11 {  
  2.  public static void main(String[] args) {  
  3.   String str = "CSharpCorner";  
  4.   String str1 = str;  
  5.   String str2 = new String("CSharpCorner");  
  6.   System.out.print("str.equals(str1) : ");  
  7.   if (str.equals(str1)) {  
  8.    System.out.println("True");  
  9.   } else {  
  10.    System.out.println("False");  
  11.   }  
  12.   System.out.print("str == str1 : ");  
  13.   if (str == str1) {  
  14.    System.out.println("True");  
  15.   } else {  
  16.    System.out.println("False");  
  17.   }  
  18.   System.out.print("str1.equals(str2) : ");  
  19.   if (str1.equals(str2)) {  
  20.    System.out.println("True");  
  21.   } else {  
  22.    System.out.println("False");  
  23.   }  
  24.   System.out.print("str1 == str2 : ");  
  25.   if (str1 == str2) {  
  26.    System.out.println("True");  
  27.   } else {  
  28.    System.out.println("False");  
  29.   }  
  30.   System.out.print("str1.equals(\"CSharpCorner\") : ");  
  31.   if (str1.equals("CSharpCorner")) {  
  32.    System.out.println("True");  
  33.   } else {  
  34.    System.out.println("False");  
  35.   }  
  36.   System.out.print("str1==\"CSharpCorner\" : ");  
  37.   if (str1 == "CSharpCorner") {  
  38.    System.out.println("True");  
  39.   } else {  
  40.    System.out.println("False");  
  41.   }  
  42.  }  
  43. }   
Output:
  1. str.equals(str1): True  
  2. str == str1: True  
  3. str1.equals(str2): True  
  4. str1 == str2: False  
  5. str1.equals("CSharpCorner"): True  
  6. str1 == "CSharpCorner": True