Java 中的默认值和初始化 [英] Default values and initialization in Java

查看:30
本文介绍了Java 中的默认值和初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于我的参考,原始类型有默认值和对象为空.我测试了一段代码.

Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.

public class Main {
    public static void main(String[] args) {
        int a;
        System.out.println(a);
    }
}

System.out.println(a); 将是一个错误,指向变量 a 表示 变量 a 可能尚未初始化 而在给定的引用中,integer 会将 0 作为默认值.但是,使用下面给定的代码,它实际上会打印 0.

The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.

public class Main {
    static int a;
    public static void main(String[] args) {
        System.out.println(a);
    }
}

第一个代码可能有什么问题?类变量的行为是否与局部变量不同?

What could possibly go wrong with the first code? Do class variables behave different from local variables?

推荐答案

在第一个代码示例中,a 是一个 main 方法局部变量.方法局部变量在使用前需要初始化.

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

在第二个代码示例中,a是类成员变量,因此会被初始化为默认值.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

这篇关于Java 中的默认值和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆