Initialization by default in java

I have a confusion regarding the initialization of variables in Java. As I understand it, class variables get initialized by default, and by default local variables are not initialized. However, if I create an array inside the method using a new keyword, it is initialized by default. Is this true for all objects? Does the new keyword use object initialization regardless of whether it is a class variable or a local variable?

+8
java initialization
source share
3 answers

Is this true for all objects? Does the new keyword use the object to initialize whether it is a class variable or a local variable?

When using the new keyword. this means that you have initialized your object. it doesn’t matter if it is declared at the method level or instance level.

 public void method(){ Object obj1;// not initialized Object obj2 = new Object();//initialized } 
+2
source share

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 a byte of type, the default value is zero, that is, the value (Byte) is 0.

  • For type short, the default value is zero, that is, the value (short) is 0.

  • For the int type, the default value is zero, i.e. 0.

  • For the long type, the default value is zero, that is, 0L.

  • For float, the default value is positive zero, i.e. 0.0f.

  • For the double type, the default value is positive zero, that is, 0.0d.

  • For the char type, the default value is the null character, i.e. '\ u0000'.

  • For the boolean type, the default value is false.

  • For all reference types (§4.3), the default value is null

+27
source share

After further investigation, primitives will always be initialized by default only if they are member variables, local variables will cause a compilation 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 that you need to create for each of them.

+5
source share

All Articles