Object Value Equality – Basic Elements, Primitive Data Types, and Operators

Object Value Equality

The Object class provides the method public boolean equals(Object obj), which can be overridden (§5.1, p. 196) to give the right semantics of object value equality. The default implementation of this method in the Object class returns true only if the object is compared with itself, as if the equality operator == had been used to compare aliases of an object. Consequently, if a class does not override the semantics of the equals() method from the Object class, object value equality is the same as object reference equality.

Certain classes in the Java SE API override the equals() method, such as java.lang.String and the wrapper classes for the primitive data types. For two String objects, value equality means they contain identical character sequences. For the wrapper classes, value equality means the wrapper objects have the same primitive value and are of the same wrapper type (see also §8.3, p. 432).

Click here to view code image // Equality for String objects means identical character sequences.
String movie1 = new String(“The Revenge of the Exception Handler”);
String movie2 = new String(“High Noon at the Java Corral”);
String movie3 = new String(“The Revenge of the Exception Handler”);
boolean test0 = movie1.equals(movie2);             // false.
boolean test1 = movie1.equals(movie3);             // true.

// Equality for wrapper classes means same type and same primitive value.
Boolean flag1 = true;                              // Boxing.
Boolean flag2 = false;                             // Boxing.
boolean test2 = flag1.equals(“true”);              // false. Not same type.
boolean test3 = flag1.equals(!flag2);              // true. Same type and value.

Integer iRef = 100;                                // Boxing.
Short sRef = 100;                                  // Boxing <— short <— int
boolean test4 = iRef.equals(100);                  // true. Same type and value.
boolean test5 = iRef.equals(sRef);                 // false. Not same type.
boolean test6 = iRef.equals(3.14);                 // false. Not same type.

// The Pizza class does not override the equals() method, so we can use either
// equals() method inherited from the Object class or equality operator ==.
Pizza pizza1 = new Pizza(“Veggies Delight”);
Pizza pizza2 = new Pizza(“Veggies Delight”);
Pizza pizza3 = new Pizza(“Cheese Delight”);
boolean test7 = pizza1.equals(pizza2);             // false.
boolean test8 = pizza1.equals(pizza3);             // false.
boolean test9 = pizza1 == pizza2;                  // false.
pizza1 = pizza2;                                   // Creates aliases.
boolean test10 = pizza1.equals(pizza2);            // true.
boolean test11 = pizza1 == pizza2;                 // true.