Java变量的初始化

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 先初始化静态比变量和静态块,然后在初始化非静态变量和块,这些都在构造方法调用前调用。

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.

从输出结果验证了上面的理论,并且如果多个相同类型(此处指的是静态和非静态)的变量或块,则按照顺利来初始化。
对于静态的只在class第一次加载的时候初始化,并且初始化一次

本地变量

对于方法内的变量,如果在定义的时候没有初始化,Java会随机赋值,对于没有赋初始值的变量,在使用的时候,编译器会发出警告。

你可能感兴趣的:(Java变量的初始化)