Default initialization of of detail based on java variables and scopes and member variables

  • 2020-12-05 17:12:31
  • OfStack

ava variables in a member variable and a local variable, method defined in the class of variables become a member or members of the field (domain), said a class of property, defined as a member of the class variables of the function and the whole class, at the time of definition does not need to initialize the variable, java automatically initialized before use member variables, for the basic data types of automatic initialization is as follows:

Default initialization values for java base types

int 0
short 0
byte 0
long 0
float 0.0
double 0.0
boolean false
char 0

Such as:


public class test{
 private int i;
 private short m;
 private byte n;
 private long l;
 private char c;
 private float f;
 private double d;
 private boolean b;
 
 public static void main(String args[]){
  System.out.println(i);
  System.out.println(m);
  System.out.println(n);
  System.out.println(l);
  System.out.println(c);
  System.out.println(f);
  System.out.println(d);
  System.out.println(b);
 }
 
}

The output of the above code will be the default initialized value;

Variables of reference type are initialized to null by default. Although java will automatically initialize member variables, automatic initialization will bring 1 error. Therefore, it is better to initialize variables before using them to ensure that the variables are used in accordance with the desired effect. The default initialization is only valid for Java member variables, which must be initialized if local variables are to be used, or you will get a compilation error.

java and 1 sample using curly braces c language to distinguish between the start and stop position and block the variables in the only valid before the end of the block of code, beyond the code block after the variable is not visible is not available, for object, its scope is 1 straight know the object visible reclaimed by the garbage collector memory, such as:


String s1 = new String("Hello world!");

The visibility of the reference variable s1 disappears at the end of the scope, but the String object created will remain 1 in memory until the java garbage collector reclaims its memory. Although the String object will remain 1 in memory, it is not available because there is no reference to it.


Related articles: