Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are fields initialized by the default constructor

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?

like image 770
Piyush Kumar Avatar asked Feb 28 '26 16:02

Piyush Kumar


1 Answers

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.

like image 142
Zabuzard Avatar answered Mar 02 '26 04:03

Zabuzard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!