some fragment of thinking in java part2

1.  What is finalize() for

the need for finalize() is limited to special case in which your object can allocate storage in some way other than creating an object

Remember that neither garbage collection nor finalization is guaranteed, if the JVM isn't close to running out of memory, then it might not waste time recovering memory througn garbage colletion.

System.gc() is used to force finalization.

2.  Initialization

void f() {

  int i;

  i++; // Error -- i not initialized

}

you will get an error message that say that i might not have been initialized. of course, the compiler could have given i a defalut value, but an uninitialized local variable is probably a programmer error, and a default value would have covered that up, Forcing the programmer to provide an initialization value is more like to catch a bug;

import static net. mindview.util.Print.*;

public  class InitialValues {

  boolean t;

  char c;

  byte b;

  short s;

  int i;

  long l;

  float f;

  double d;

  InitialValues reference;

  void printInitialValues() {

    print("Data type    Initial Value");

    print("boolean      "  +  t);

    print("char           "  +  c);

    print("int             "  +  i);

    .......

    print(reference     " + reference);

  }

  public static void void main(String[] args) {

    InitialValue iv = new InitialValues();

    iv.printInitialValues();

    /* you could also say:

    new InitialVaule().printInitialValues();

    */

  }

}  /* output

  Data type      Intial value

  boolean         false

  char              [ ]

  byte               0

  ......

  double           0.0

  reference        null

*/

you can see that even though the values are not specified, they automatically get initialized(the char is a zero, which prints as a sapce). so at least there's no threat of working with uninitialized variables. since the object has not be initialized, the value is null.

3. Order of initialization

within a class, the order of initialization is determined by the order that the variable are defined within the class and the variables are initialized before any method can be called--even the constructor. the static variables are initialized before the other variables, the static methods take place only once, as the Class object is loaded for the first time as well as the static variables.

 

posted on 2015-10-21 20:58  terminator-LLH  阅读(271)  评论(0编辑  收藏  举报

导航