Tuesday, February 11, 2014

Java / String equals() vs "=="

Comparing Strings in Java.

public class Main 
{
 
 public static void main(String[] args)
 { 
  String a = new String("abcd");
  String b = new String("abcd");
    
  if(a == b)
   System.out.println("true");
  else
   System.out.println("false");
  
  if(a.equals(b))
   System.out.println("true");
  else
   System.out.println("false");
 }  
}

The output will be:
false
true

Explanation:
The operator "==" check if String "a" and String "b" refers to the same object - to the same place in the memory.
Method equals() compare the content of Strings (content of two objects).

Take a look at second example;

public class Main 
{
 
 public static void main(String[] args)
 { 
  String a = new String("abcd"); 
  String b = a;
    
  if(a == b)
   System.out.println("true");
  else
   System.out.println("false");   
 }  
}

Now the result is:
true
true

Explanation:
The operator "==" check if String "a" and String "b" refers to the same object. Yes, it refers to the same object (String b = a;).

Remember:
The operator "==" check if objects refers to the same memory location.
Method equals() check the value of the object.

No comments: