Operators and Assignments - Boolean equals()
- defined in java.lang.Object therefore inherited by all classes
- returns true if and only if the two variables being compared hold a reference to the same object
To check if objects are of the same class use the
Comparison operator:
instanceof
Class_A a = new Class_A();
Class_B b = new Class_B();
Class_C c = new Class_A();
Class_B d = b;
Class_A e = null;
a.equals(b) // false (different obj refs)
a.equals(c) // false (different obj refs)
b.equals(d) // true (same object refs)
a.equals(e) // false (always returned when
// compared to a null)
- java.lang.String overrides the java.lang.Object equals() method to return true if and only if the objects being compared contain the same sequence of characters.
String s0 = "Hello";
String s1 = new String("Hello"); // force new string object
String s2 = s0;
s0.equals(s1) // true (diff objects, same chars)
s0.equals(s2) // true (same chars, coincidence
// they are same objects)
- java.lang.Boolean overrides the java.lang.Object equals() method, returning true if and only if the Boolean objects represent the same boolean value
Boolean b0 = new Boolean(true);
Boolean b1 = new Boolean(false);
Boolean b2 = new Boolean(true);
Boolean b3 = b1;
b0.equals(b1) // false (different boolean values)
b0.equals(b2) // true (same boolean values)
b1.equals(b3) // true (same boolean values)
| FYI |
|
You cannot assign values to Boolean types with either of the following constructs:
|
Boolean b3 = new Boolean();
boolean b4 = true;
b3 = b4; // compile-error: incompatible types
b3 = true; // compile-error: incompatible types
|
Example Code
Tips
- all the primitive type wrapper classes override the Object.equals() method to compare the value of the objects; the default Object.equals() checks if the variables reference the same object
|