1. For a class member variable, the Java virtual machine automatically initializes it to its default value, regardless of whether the program has been explicitly initialized.
The default values are as follows:
Boolean false
Char ' \u0000 ' (null)
BYTE (byte) 0
Short (short) 0
int 0
Long 0L
Float 0.0f
Double 0.0d
2. After a local variable is declared, the Java Virtual machine does not automatically initialize it to its default value, so the use of local variables must first be explicitly initialized.
However, it is necessary to declare that local variables that are only responsible for receiving the value of an expression can be uninitialized, and that local variables that participate in other situations, such as operations and direct output, need to be initialized.
The following test allows you to see which data the JVM initializes, and which data is not initialized:
Public class Teststatic {
static int x; //class member variable, JVM is responsible for initializing
static int method ()
{
int y=0; //must initialize itself here, it does not belong to a class member variable, is a local variable of method, the JVM is not responsible for initializing
return y;
}
public static void Main (string[] args) {
Teststatic as=new teststatic ();
int z=0; You must initialize it yourself here, it is not a class member variable, it is a local variable in the main function, the JVM is not responsible for initialization
int aa=3; //Here AA participates in the operation, so it must be initialized
aa=aa+2;
int A=1,b=2,max; //max is only responsible for receiving the value of the expression and does not need to initialize
max=a>b?2:1;
SYSTEM.OUT.PRINTLN (max); 1
SYSTEM.OUT.PRINTLN (AA); 5
System.out.println ("z=" +z); Z=0
System.out.println ("x=" +as.x); X=0
System.out.println ("y=" +as.method ()); Y=0
}
}
summed up in a sentence is:
A data member defined in a class is called a property, and a property is not assigned an initial value, and Java adds default values to the table if it is not assigned, and the data member defined in the method is called a variable, and the variable must have an initial value assigned before it participates in the operation.
Initialization of Java variables (reprint)