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会随机赋值,对于没有赋初始值的变量,在使用的时候,编译器会发出警告。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 35,088评论 18 399
  • 父类 static 块 1 执行 父类 静态成员staticSam1初始化 父类 静态成员staticSam2初始...
    YCix阅读 1,419评论 0 0
  • Win7下如何打开DOS控制台? a:开始--所有程序--附件--命令提示符 b:开始--搜索程序和文件--cmd...
    逍遥叹6阅读 1,737评论 4 12
  • 我一直希望, 希望有一首诗。 讲的是仙台佳话 说的是柴米油盐。 酒足饭饱,然后吹水西东。 我听得见你的欢乐, 我看...
    陌上3513阅读 270评论 0 0

友情链接更多精彩内容