Java中的变量默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9687634/
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
Variable default value in Java
提问by Mansuro
Every type in Java has a primitive value when declared. This article contains a description for primitive data types Primitive Data Types. Knowing this, why does Eclipse show an error telling me the variable may not have been initialized? If I have for example
Java 中的每个类型在声明时都有一个原始值。本文包含对原始数据类型Primitive Data Types 的描述。知道了这一点,为什么 Eclipse 会显示一个错误,告诉我变量可能尚未初始化?如果我有例如
int x;
x++;
采纳答案by Chikei
From the link
从链接
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 Tom
Local variables don't get initialized.
局部变量不会被初始化。
This is a local variable:
这是一个局部变量:
void aaa() {
int x;
}
This is an instance variable. These do get initialized automatically:
这是一个实例变量。这些确实会自动初始化:
class X {
int x;
}
回答by Churk
What you see is not an error but your eclipse preference. You can change it to ignore un-initialized variables in eclipse preference.
您看到的不是错误,而是您的日食偏好。您可以将其更改为忽略 eclipse 首选项中未初始化的变量。
回答by Soteric
From the Primitive Data Types link provided by you: "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 hmjd
From the Java Language Specification, Java SE 8 Edition, 4.12.5 Initial Values of Variables:
来自Java Language Specification, Java SE 8 Edition, 4.12.5 Initial Values of Variables:
A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).
局部变量(第 14.4 节、第 14.14 节)必须在使用前通过初始化(第 14.4 节)或赋值(第 15.26 节)明确指定一个值,其方式可以使用明确赋值规则(第16(明确分配))。
回答by Mr. Suryaa Jha
Data Type Default Value (for fields)
数据类型默认值(用于字段)
byte 0
字节 0
short 0
短 0
int 0
整数 0
long 0L
长0L
float 0.0f
浮动 0.0f
double 0.0d
双0.0d
char ‘u0000'
字符'u0000'
String (or any object) null
字符串(或任何对象) null
boolean false
布尔假