Object is an instance of a class. We create an object with keyword new and a constructor.
Date d = new Date();
In this statement, Date d is a reference variable refers to the object created, new Date() creates the object. Date() is a constructor, it is a special method that creates a new object.
Constructor's name have to match that of the class, and there is no return type.
class Tree {
public Tree() {System.out.print("a tree!");}
public void Tree() {} //not constructor
}
Objects are stored in java program's memory heap. Java have a process called garbage collection -- for those object no longer reachable, they are automatically deleted from memory heap. An object became unreachable when there is no reference variable refers to it or the object run out of scope.
As programmer, we can not control when garbage collection will happen. The statement System.gc(); only suggests JVM this is a good time to collect garbage. Function protected void finalize() is called once and only once when the object is garbage collected.
OCA tests objects' lifecycle, it is easier to answer those questions if we trace reference variables by drawing links to objects.
OCAJP>cat GC.java
import java.util.Date;
class GC{
public static void main(String args[]) {
GC objref = new GC(); //objref --> GCobj1
objref.demo();
System.gc(); //suggest JVM it is a good point to garbage collection, JVM may ignor
objref = new GC(); //objref --> GCobj2, GCobj1 is ready for garbage collection
objref = null; //GCobj2 is ready for garbage collection
//try to create lots of garbage
for(int i = 1; i < 5; i++) {new Date(); System.gc();}
}
/*JVM calls this during garbage collection.
* When GCobj1 and GCobj2 are garbage collected,
* "in finalizer" can possibilily be printed twice.
* However, there is no garentee the garbage collection will happen at all.
*/
protected void finalize() {System.out.println("in finalizer");}
private void demo() {
Date ref1 = new Date(); //ref1 -->object1;
Date ref2 = new Date(); //ref2 -->object2; ref1 -->object1
Date ref3 = ref1; //ref3, ref1 --> object1; ref2 --> object2
Date ref4 = ref1; //ref4, ref3, ref1 --> object1; ref2 --> object2
ref4 = ref2; //ref4, ref2 --> object2; ref3, ref1 --> object1
ref4 = null; //ref2 --> object2; ref3, ref1 --> object1
ref2 = ref1; //ref3, ref2, ref1 --> object1, object2 is ready for garbage collection
}//ref1, ref2, ref3 run out of scope, object1 is read for garbage collection
}
OCAJP>javac GC.java
OCAJP>java GC
OCAJP>java GC
in finalizerOCAJP>
OCAJP>java GC
OCAJP>java GC
in finalizerOCAJP>java GC
OCAJP>java GC
in finalizer
OCAJP>java GC
in finalizerOCAJP>java GC
in finalizerOCAJP>java GC
in finalizer
OCAJP>java GC
in finalizer
in finalizerOCAJP>
see also: JVM optimization for java 8
Back OCAJP