equals( ) vs ==

equals( ) method and the == operator perform two different operations. equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

The following program shows the differences:


public class Main {
  public static void main(String args[]) {
    String s1 = "java2s.com";
    String s2 = new String(s1);

    System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
    System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
  }
}
  

Here is the output of the preceding example:


java2s.com equals java2s.com -> true
java2s.com == java2s.com -> false
  
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.