Java 中的默认值和初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19131336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default Values and Initialization in Java
提问by Michael 'Maik' Ardan
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
.
该行将System.out.println(a);
是一个错误,指向变量a
,variable a might not have been initialized
而在给定的引用中,integer
将具有0
默认值。但是,使用下面给定的代码,它实际上会打印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 instancevariable behaves different from local variables?
第一个代码可能会出什么问题?类实例变量的行为是否与局部变量不同?
采纳答案by Juned Ahsan
In the first code sample, a
is a main
method local variable. Method local variables need to be initialized before using them.
在第一个代码示例中,a
是一个main
方法局部变量。方法局部变量在使用前需要初始化。
In the second code sample, a
is class member variable, hence it will be initialized to default value .
在第二个代码示例中,a
是类成员变量,因此它将被初始化为默认值。
回答by upog
yes, instance variable will be initialized to default value, for local variable you need to initialize before use
是的,实例变量会被初始化为默认值,对于局部变量你需要在使用前进行初始化
public class Main {
int instaceVariable; // Instance variable will be initalized to default value
public static void main(String[] args) {
int localVariable = 0; // Local Variable Need to initalize before use
}
}
回答by newuser
All member variable have to load into heap so they have to initialized with default values when an instance of class is created. In case of local variables, they don't get loaded into heap they are stored in stack until they are being used before java 7, so we need to explicitly initialize them.
所有成员变量都必须加载到堆中,因此在创建类的实例时必须使用默认值进行初始化。在局部变量的情况下,它们不会被加载到堆中,它们存储在堆栈中,直到它们在 java 7 之前被使用,因此我们需要显式初始化它们。
回答by Paolo
Read more carefully your reference:
更仔细地阅读您的参考资料:
Default Values
It's not always necessary to assign a value when a fieldis declared. Fieldsthat are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
. . .
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
默认值
声明字段时并不总是需要赋值。 已声明但未初始化的字段将由编译器设置为合理的默认值。一般而言,此默认值将为零或空值,具体取决于数据类型。然而,依赖这样的默认值通常被认为是糟糕的编程风格。
下图总结了上述数据类型的默认值。
. . .
局部变量略有不同;编译器永远不会为未初始化的局部变量分配默认值。如果您无法在声明它的地方初始化您的局部变量,请确保在尝试使用它之前为其分配一个值。访问未初始化的局部变量将导致编译时错误。
回答by ramesh
In java the default initialization is applicable for only instance variable of class member it isn't applicable for local variables.
在 java 中,默认初始化仅适用于类成员的实例变量,不适用于局部变量。
回答by Kostas Chalkias
These are the main factors involved:
这些是涉及的主要因素:
- member variable (default OK)
- static variable (default OK)
- final member variable (not initialized, must set on constructor)
- final static variable (not initialized, must set on a static block {})
- local variable (not initialized)
- 成员变量(默认 OK)
- 静态变量(默认 OK)
- final 成员变量(未初始化,必须在构造函数上设置)
- 最终静态变量(未初始化,必须在静态块 {} 上设置)
- 局部变量(未初始化)
Note 1: you must initialize final member variables on EVERY implemented constructor!
注意 1:您必须在每个实现的构造函数上初始化 final 成员变量!
Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is NOT valid:
注意2:必须在构造函数本身的块内初始化final成员变量,而不是调用另一个初始化它们的方法。例如,这是无效的:
private final int memberVar;
public Foo() {
//invalid initialization of a final member
init();
}
private void init() {
memberVar = 10;
}
Note 3: arrays are Objects in Java, even if they store primitives.
注意 3:数组在 Java 中是对象,即使它们存储基元。
Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.
注意 4:当你初始化一个数组时,它的所有项都被设置为默认值,独立于成员或本地数组。
I am attaching a code example, presenting the aforementioned cases:
我附上一个代码示例,介绍上述案例:
public class Foo {
//static and member variables are initialized to default values
//primitives
private int a; //default 0
private static int b; //default 0
//objects
private Object c; //default NULL
private static Object d; //default NULL
//arrays (Note: they are objects too, even if they store primitives)
private int[] e; //default NULL
private static int[] f; //default NULL
//what if declared as final?
//primitives
private final int g; //not initialized, MUST set in constructor
private final static int h; //not initialized, MUST set in a static {}
//objects
private final Object i; //not initialized, MUST set in constructor
private final static Object j; //not initialized, MUST set in a static {}
//arrays
private final int[] k; //not initialized, MUST set in constructor
private final static int[] l; //not initialized, MUST set in a static {}
//initialize final statics
static {
h = 5;
j = new Object();
l = new int[5]; //elements of l are initialized to 0
}
//initialize final member variables
public Foo() {
g = 10;
i = new Object();
k = new int[10]; //elements of k are initialized to 0
}
//A second example constructor
//you have to initialize final member variables to every constructor!
public Foo(boolean aBoolean) {
g = 15;
i = new Object();
k = new int[15]; //elements of k are initialized to 0
}
public static void main(String[] args) {
//local variables are not initialized
int m; //not initialized
Object n; //not initialized
int[] o; //not initialized
//we must initialize them before usage
m = 20;
n = new Object();
o = new int[20]; //elements of o are initialized to 0
}
}
回答by Ani
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
局部变量没有默认值。它们的初始值是未定义的,没有通过某种方式分配值。在你可以使用局部变量之前,它们必须被初始化。
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
在类级别(作为成员,即作为字段)和方法级别声明变量时有很大的不同。
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.
如果您在类级别声明一个字段,它们将根据其类型获得默认值。如果您在方法级别或作为块声明变量(意味着 {} 内的任何代码),则不会获得任何值并保持未定义状态,直到它们以某种方式获得一些起始值,即分配给它们的某些值。
回答by Pritam Banerjee
There are a few things to keep in mind while declaring primitive type values.
在声明原始类型值时需要记住一些事情。
They are:
他们是:
- Values declared inside a method will not be assigned a default value.
- Values declared as instanced variable or a static variable will have default values assigned which is 0.
- 在方法中声明的值不会被分配默认值。
- 声明为实例变量或静态变量的值将分配默认值为 0。
So in your code:
所以在你的代码中:
public class Main {
int instanceVariable;
static int staticVariable;
public static void main(String[] args) {
Main mainInstance = new Main()
int localVariable;
int localVariableTwo = 2;
System.out.println(mainInstance.instanceVariable);
System.out.println(staticVariable);
// System.out.println(localVariable); //will throw compilation error
System.out.println(localVariableTwo);
}
}