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?
-
1Did you try it out to see what happens?Justin Jasmann– Justin Jasmann2013-03-01 19:22:30 +00:00Commented Mar 1, 2013 at 19:22
-
Yeah, I tried with other objects and that's what seems to happen, which is why I asked the questionB M– B M2013-03-01 19:24:35 +00:00Commented Mar 1, 2013 at 19:24
3 Answers
From Java Language Specification
Each class variable, instance variable, or array component is initialized with a default value when it is created (§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
2 Comments
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.
6 Comments
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?
When you use new keyword. it means that you have initialized your Object. doesn't matter if its declared at method level or instance level.
public void method(){
Object obj1;// not initialized
Object obj2 = new Object();//initialized
}