Inside class(类), primitives(原始类型) are given default values if you don’t specify values, If you haven’t given “i” an initial value and you try to use it anyway, you’ll get a runtime error called an exception.
void f() { // Error -- the local variable i may not initialized int i; i++; int [] a, b; // that's right, array 'a' has been initialized a = new int[5]; // wrong, since 'b' is an array b = 2; // right, its result is default 0 System.out.print(a[0]); } class Data { int i = 999; // Defaults to zero long l; }Order of initialization – Order that variables/objects are defined in class. Let’s see.
1、
class Counter { int i; // i will first be initialized to 0, then to 7 Counter() { i = 7; } }2、
class Card { // Before constructor 1 Tag t1 = new Tag(1); // Then constructor 4 Card() { // Indicate we're in the constructor: System.out.println("Card()"); // Reinitialize t3 t3 = new Tag(33); } // Before constructor 2 Tag t2 = new Tag(2); // At last, method void f() { System.out.println("f()"); } // Before constructor 3 Tag t3 = new Tag(3); }1、The first time an object of type Dog is created, or the first time a static method or static field of class Dog is accessed. 2、As Dog.class is loaded, all of its static initializers are run. 3、The construction process for a Dog object first allocates enough storage for a Dog object on the heap. 4、This storage is wiped to zero, automatically setting all the primitives in that Dog object to their default values. 5、Any initializations that occur at the point of field definition are executed. 6、Constructors are executed.
Java allows you to group other static initializations inside a special “static clause” (sometimes called a static block) in a class. like other static initializations, is executed only once.
Cleanup: Finalization and Garbage Collection
1、Garbage collection is not destruction 2、Your objects may not get garbage collected 3、Garbage collection is only about memory
1、In theory: releasing memory that the GC wouldn’t 2、It’s never been reliable: promises to be called on system exit; (causes bug in Java file closing) 3、Using finalize() to detect an object that hasn’t been properly cleaned up 4、finalize() is only useful for obscure memory cleanup that most programmers will never use
1、Must write specific cleanup method
Java GC releases memory only: any other cleanup must be done explicitly!
