Xelian
Xelian

Reputation: 17208

Who trigger the initialization of primitive types?

I was wondering who/what trigger the initialization of the primitive types in Java for example:

public class A {
    int primitive;
    String nonPrimitive;

    public static void main(String[] args) {
        A newObject = new A();
    }
}

So when we create the new instance of A, the default constructor of A class is called. String extends Object, so then the constructor of Object is called and nonPrimitive var has been created and have null value.

But what is the situation with primitive variable? If it is initialized directly by the VM with default value 0 and if the creation of the new newObject triggered it? Or it is created before creating the newObject?

Upvotes: 1

Views: 73

Answers (1)

Maroun
Maroun

Reputation: 95958

When the object is created, its fields are created.

new A();

The fields are initialized, each with its default value - according to what's stated in the JLS 4.12.5. Initial Values of Variables:

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

That's why String is initialized with null. See the full table to see other values (yes, integer class variables are set to 0 by default).

See also 12.4.1. When Initialization Occurs, it explains in details what happens when class is initialized.

Upvotes: 5

Related Questions