java java中的默认初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15165238/
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 initialization in java
提问by B M
I have a confusion about variable initialization in Java. As I understand, class variables get default initialization while local variables are not initialized by default. However, if I create an array inside a method using the new keyword, it does get initialized by default. Is this true of all objects? Does using the new keyword initialize an object regardless of whether it's a class variable or local variable?
我对 Java 中的变量初始化感到困惑。据我了解,类变量默认初始化,而局部变量默认不初始化。但是,如果我使用 new 关键字在方法中创建一个数组,默认情况下它会被初始化。所有对象都是这样吗?无论对象是类变量还是局部变量,都使用 new 关键字初始化对象吗?
采纳答案by PermGenError
Is this true of all objects? Does using the new keyword initialize an object regardless of whether it's a class variable or local variable?
所有对象都是这样吗?无论对象是类变量还是局部变量,都使用 new 关键字初始化对象吗?
When you use new
keyword. it means that you have initializedyour Object. doesn't matter if its declared at method level or instance level.
当您使用new
关键字时。这意味着您已经初始化了您的对象。它是在方法级别还是实例级别声明都没有关系。
public void method(){
Object obj1;// not initialized
Object obj2 = new Object();//initialized
}
回答by iTech
From Java Language Specification
Each class variable, instance variable, or array componentis initialized with a default value when it is created (§15.9, §15.10):
每个类变量、实例变量或数组组件在创建时都使用默认值进行初始化(第 15.9 节、第 15.10 节):
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null
对于byte类型,默认值为0,即(byte)0的值。
对于short类型,默认值为0,即(short)0的值。
对于 int 类型,默认值为 0,即 0。
对于 long 类型,默认值为零,即 0L。
对于 float 类型,默认值为正零,即 0.0f。
对于 double 类型,默认值为正零,即 0.0d。
对于char类型,默认值为空字符,即'\u0000'。
对于类型 boolean,默认值为 false。
对于所有引用类型(第 4.3 节),默认值为 null
回答by Kevin DiTraglia
After further investigation, primitives will always initialize to the default only when they are member variables, local variables will throw a compile error if they are not initialized.
经过进一步调查,原语只有在它们是成员变量时才会始终初始化为默认值,局部变量如果没有初始化就会抛出编译错误。
If you create an array of primitives they will all be initialized by default (this is true for both local and member arrays), an array of objects you will need to instantiate each one.
如果您创建一个原始数组,它们将在默认情况下全部初始化(对于本地数组和成员数组都是如此),您需要实例化每个对象数组。