Non-final method of java.lang.Object
class.
Definition of Object.equals():
public boolean equals(Object obj) {
return (this == obj);
}
To compare the object contents/state, the programmer should override the equals()
method.
Properties of equals()
method:
x
, x.equals(x)
should return true
.x
and y
, x.equals(y)
should return true
if and only if y.equals(x)
returns true
.x
, y
, and z
, if x.equals(y)
returns true
and y.equals(z)
returns true
, then x.equals(z)
should return true
.x
and y
, multiple invocations of x.equals(y)
consistently return true
or consistently return false
, provided no information used in equals comparisons on the objects is modified.x
, x.equals(null)
should return false
.class Employee {
// ...
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(this == obj)
return true;
if(! (obj instanceof Employee))
return false;
Employee other = (Employee) obj;
if(this.id == other.id)
return true;
return false;
}
}
Garbage collection is automatic memory management by JVM.
If a Java object is unreachable (i.e. not accessible through any reference), then it is automatically released by the garbage collector.
An object become eligible for GC in one of the following cases:
Nullifying a reference:
MyClass obj = new MyClass();
obj = null;
Reassigning a reference:
MyClass obj = new MyClass();
obj = new MyClass();
Object created locally in a method:
void method() {
MyClass obj = new MyClass();
// ...
}
GC is a background thread in JVM that runs periodically and reclaim memory of unreferenced objects.
Before object is destroyed, its finalize() method is invoked (if present).
One should override this method if object holds any resource to be released explicitly e.g. file close, database connection, etc.