Tuesday, February 12, 2013

SCJP: equals and ==

The difference between == and equals
== compares if two references points to the same object
equals uses its own logic to compare if two objects are equal

==
To save memory, two instances of the following wrapper objects will always be == when their primitive values are the same (in a range from -128 to 127 for Short, Integer and Byte; values from '\u0000' to '\u007f' for Character; Boolean).

Integer one = 127;
Integer two = 127;

if(one==two)
  System.out.println("Same");

This will print Same.


But this will print Different (because the object references are different):

Integer one = new Integer(127);
Integer two = new Integer(127);

if(one==two)
  System.out.println("Same");
else
  System.out.println("Different");


And this will also print Different (it is out of the pool range from -128 to 127):

Integer one = 128;
Integer two = 128;

if(one==two)
  System.out.println("Same");
else
  System.out.println("Different");


String == and equals
String one = “today”;
String two = “today”;
if(one == two)
  System.out.println(“true”);
else
  System.out.println(“false”);

This will print true, because all the string literals are stored by the JVM in the string pool, and since they are immutable, instances in the string pool can be shared, so they are referring to the same object.


String one = “today”;
String three = new String(“today”);
if(one == three)
  System.out.println(”true”);
else
  System.out.println(“false”);

This will print false, because the one points to string that lives in the string pool while three represents a dynamically created string (it does not live in the string pool)

Comparing Wrapper to primitive value
When comparing a Wrapper to a primitive, auto-unboxing occurs and the comparison is performed primitive to primitive.

equals
For Wrapper classes, two objects are equals if they are of the same type and have the same value.
Please regard that StringBuffer does not override equals (so, cannot compare values), but StringBuilder does override equals (compares values).

No comments:

Post a Comment