May I know how ==
works here?
public class App {
public static void main(String[] args) {
String s1 = new String("str");
String s2 = new String("str");
System.err.println("why it,s "+String.valueOf(s1==s2));
int i1 = new Integer(10);
int i2 = new Integer(10);
System.err.println("why it,s "+String.valueOf(i1==i2));
}
}
When I am comparing references of two different String
with the same values, then ==
says that they are not equal, but when I am comparing references of two integers with the same values, then ==
says that they are equal. Why is it so?
Ok, a more meaningful compare would be
int
is primitive, and == will just compare the value.Integer
is an object, and == for objects is only true if it points to the same place in memory, otherwise it will be false. For primitives (int, boolean, etc...) == will test the value.int i = Integer(10)
is reallyint i = (Integer(10)).intValue()
, java just does it automagically.Edited to add more explanation:
Java has 2 types of types. Primitive types and Class types. A primitive type is just the value of the type: an int primitive type is just that, and int. There are not methods or anything, it just is an int.
If you say
int a = 4
, a is a primitive variable that points to a memory address that contains an int. That's it.A Class type is a java object, so Integer is a class type. It represents an integer value, so
Integer a = new Integer(4)
would create an integer object, and a would point to a memory location that contains the object that new... created.What's different?
Good question. In the latter example (new Integer(4)) this is an integer and some other stuff, stuff like a
toString()
method and some other stuff.So, a recap:
A primitive is a value stored in memory somewhere. A class is an object stored in memory somewhere, and in the case of Integer it represents an int but it has some other stuff associated with it (i.e. the `toString() method).
Now, == is a test for equivalency. So
int == int
checks to see if the primitive value is the same, since that is the only information that a primitive type has.== for objects does mean something. Since an object points to a more than just a 4 or 8 or -1, the == only returns true if the object variables point to the same place in memory. If it does not, then you get false.
So:
Now, .equals is a test to see if two objects are equal, which means different things for different objects.
For an Integer, a.equals(b) is true if the intValue()s are the same for a and b. However, a == b is true if a and b point at the same object in memory
Now, thing about an object that has 2 integers in it (like an x,y coordinate).