Click here to Skip to main content
13,905,482 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 24 Nov 2011
Licenced CPOL

equals( ) Versus == in Java(Android)

, 24 Nov 2011
Rate this:
Please Sign up or sign in to vote.
It is important to understand that the equals( ) method and the == operator perform two different operations.
As just explained, the 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 how two different String objects can contain the same characters, but references to these objects will not compare as equal:

// equals() vs ==
   class EqualsNotEqualTo {
   public static void main(String args[]) {
   String s1 = "Hello";
   String s2 = new String(s1);
   System.out.println(s1 + " equals " + s2 + " -> " +
   System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

Hello equals Hello -> true
Hello == Hello -> false


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190306.1 | Last Updated 24 Nov 2011
Article Copyright 2011 by Jaydeep Jadav
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid