equals() vs == in JAVA

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.

Ex: public class Main { public static void main(String args[]) {
String s1 = "demo2s.com";
String s2 = new String(s1);
// ww w.j a v a 2 s .com
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}

Result:
demo2s.com equals demo2s.com -> true
demo2s.com == demo2s.com ->false
Previous Post Next Post