What is the difference between equals() method and == operator in java?


The equals() method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Example

 Live Demo

public class Sample{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
   }
}

Output

true
false

You can also compare two strings using == operator. But, it compares references of the given variables not values.

Example

 Live Demo

public class Sample{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
   }
}

Output

true
false

Updated on: 29-Jun-2020

607 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements