Difference between == and equals()?

Technology: java
AskedIn:
Topics:
Type:
  • ==  checks for the equality of references to objects (in case of comparison between object references)
  • equals() methods checks for the contents of the objects

Example

class StringDemo{  

public static void main(String[] args) {  

  String name1 = new String("Dell");  

  String name2 = new String("Dell");  

  System.out.println("Check if two strings are equal");

   // check if two strings are equal  

  // using == operator  

  boolean result1 = (name1 == name2);   

 System.out.println("Using == operator: " + result1);  

  // using equals() method    

boolean result2 = name1.equals(name2);   

 System.out.println("Using equals(): " + result2);

  }

}

 

Output

Check if two strings are equal

Using == operator: false

Using equals(): true