3

As many of the authors have written in their books that the default values of instance variables inside a class are initialized by the class-default constructor, but I have an issue understanding this fact.

class A { int x; A() {} } 

As I have provided the default constructor of class A, now how the value of x is initialised to 0?

1

1 Answer 1

5

Explanation

As written in the JLS, fields are always automatically initizialized to their default value, before any other assignment.

The default for int is 0. So this is actually part of the Java standard, per definition. Call it magic, it has nothing to do with whats written in the constructor or anything.

So there is nothing in the source code that explicitly does this. It is implemented in the JVM, which must adhere to the JLS in order to represent a valid implementation of Java (there are more than just one Java implementations).

See §4.12.5:

Initial Values of Variables

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2)


Note

You can even observe that this happens before any assignment. Take a look at the following example:

public static void main(String[] args) { System.out.println("After: " + x); } private static final int x = assign(); private static int assign() { // Access the value before first assignment System.out.println("Before: " + x); return x + 1; } 

which outputs

Before: 0 After: 1 

So it x is already 0, before the first assignment x = .... It is immediatly defaulted to 0 at variable creation, as described in the JLS.

Sign up to request clarification or add additional context in comments.

3 Comments

"It has nothing to do with constructors." I got confused by this. It's directly related to constructors since they trigger the "default value initialisation"
that's a great answer, but the "magic" you mentioned is probably what the OP wants to know
I see. Well, there is nothing in the source code that does this. It is actually implemented in the JVM which interprets and executes the source code. Every implementation of Java (there are more than one) needs to follow what is written in the JLS. So from a source code POV it is pure magic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.