Java中的默认值和初始化 [英] Default Values and Initialization in Java
问题描述
基于我的参考,原始类型具有默认值和对象为空。我测试了一段代码。
public class Main {
public static void main(String [] args){
int a;
System.out.println(a);
行 System.out .println(a);
将会是一个指向 a
变量的错误,它表示变量a可能尚未初始化
,而在给定的引用中, integer
将有 0
作为默认值。但是,使用下面给出的代码,它实际上会打印 0
。
public class Main {
static int a;
public static void main(String [] args){
System.out.println(a);
}
}
第一个代码可能会出错吗? class instance 变量的行为与局部变量的行为不同吗?
在第一个代码示例中, a
是一个 main
方法局部变量。在使用它们之前,局部变量需要初始化。
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);
}
}
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? Does class instance variable behaves different from local variables?
In the first code sample, a
is a main
method local variable. Method local variables need to be initialized before using them.
In the second code sample, a
is class member variable, hence it will be initialized to default value .
这篇关于Java中的默认值和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!