Core Java Tutorial

Core Java Tutorial

Equals vs Equalsto Operator in Java

Equals vs Equalsto:

Equals method in string class is overridden from object class to checks its value. The operator cannot be overridden in java == operator will always checks its memory where reference are pointing it.

Example:

package stat;

public class SampleString {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  String s1 = new String("Candid");

  String s2 = "Candid";
  String s3 = "Candid";


  System.out.println(s1 == s2); // check the object memory where it is created

  System.out.println(s2 == s3);


  System.out.println(s1.equals(s2)); // equals method checks the value
  System.out.println(s2.equals(s3));

 }

}
Output:
false
true
true
true