Java變量默認值
Java變量的初始化榨咐,如果不賦值璧亚,將會有個默認值,對于基本類型柱搜,比如int,long是0, boolean 是false等迟郎,引用類型如果不設置,將會是null.
package variable.initialize;
public class Test {
int intAge;
short shortAge;
long longAge;
float floatAge;
double doubleAge;
char charC;
boolean booleanFlg;
byte byteB;
String string;
private void print() {
System.out.println("The default value for int is " + intAge);
System.out.println("The default value for short is " + shortAge);
System.out.println("The default value for long is " + longAge);
System.out.println("The default value for float is " + floatAge);
System.out.println("The default value for double is " + doubleAge);
System.out.println("The default value for char is " + charC+((int)charC));
System.out.println("The default value for boolean is " + booleanFlg);
System.out.println("The default value for bayte is " + byteB);
System.out.println("The default value for String is " + string);
}
public static void main(String[] args) {
new Test().print();
}
}
輸出結果:
The default value for int is 0
The default value for short is 0
The default value for long is 0
The default value for float is 0.0
The default value for double is 0.0
The default value for char is
The default value for boolean is false
The default value for bayte is 0
The default value for String is null
初始化順序
Java 先初始化靜態(tài)比變量和靜態(tài)塊聪蘸,然后在初始化非靜態(tài)變量和塊宪肖,這些都在構造方法調用前調用。
package variable.initialize;
class Dog {
int age;
Dog(int age) {
this.age = age;
System.out.println("This is the constructor of Dog class, with age " + age);
}
}
public class Test2 {
Dog dog1 = new Dog(2);
{
System.out.println("I am a nomal block.");
}
static Dog dog2 = new Dog(3);
static{
System.out.println("I am a static block.");
}
private Test2() {
System.out.println("This is the constructor of Test class.");
}
public static void main(String[] args) {
new Test2();
}
}
輸出結果:
This is the constructor of Dog class, with age 3
I am a static block.
This is the constructor of Dog class, with age 2
I am a nomal block.
This is the constructor of Test class.
從輸出結果驗證了上面的理論健爬,并且如果多個相同類型(此處指的是靜態(tài)和非靜態(tài))的變量或塊控乾,則按照順利來初始化。
對于靜態(tài)的只在class第一次加載的時候初始化娜遵,并且初始化一次
本地變量
對于方法內的變量蜕衡,如果在定義的時候沒有初始化,Java會隨機賦值设拟,對于沒有賦初始值的變量慨仿,在使用的時候,編譯器會發(fā)出警告纳胧。