Geeg
Geeg

Reputation: 97

variable initialization by constructor

Regarding the variable x3, which constructor initializes it? I can't seem to figure it out. Would it be the no-arg constructor of class X? or maybe the default constructor of object class?

class X {
    int x1, x2, x3;
}

Upvotes: 1

Views: 321

Answers (3)

Persixty
Persixty

Reputation: 8579

They're initialized to the relevant default value (zero or null) before entering the constructor.

See this similar question (that links through to the JLS):

Which run first? default values for instance variables or Super Constructors?

Anything else would appear to be in danger of compromising the encapsulation of the Java environment. If fields weren't initialized that might expose uninitialized data and which a malicious program might be able to exploit.

Upvotes: 0

Jiri Tousek
Jiri Tousek

Reputation: 12440

public class Hello {
    private int x;
    private int y = 0;
}

This results in following class file:

public class Hello {

  // Field descriptor #6 I
  private int x;

  // Field descriptor #6 I
  private int y;

  // Method descriptor #9 ()V
  // Stack: 2, Locals: 1
  public Hello();
     0  aload_0 [this]
     1  invokespecial java.lang.Object() [11]
     4  aload_0 [this]
     5  iconst_0
     6  putfield Hello.y : int [13]
     9  return
}

If I read the above correctly:

  • y is initialized in the implicit no-args constructor
  • x is not initialized at all in any constructor
    • Java ensures that the compiler will assign a default value of 0 to it - but this initialization is not seen in the byte code, so it's probably left to compiler to decide when to initialize it (i.e. you should not rely on the variable being initialized at any particular moment - even if you determine by observation when this happens, you have no guarantee it will not change in future or between different JVMs).

Upvotes: 0

user3437460
user3437460

Reputation: 17454

x3 is a instance variable, it will have a default value of 0 (for int). From Java docs:

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.

Relying on such default values, however, is generally considered bad programming style.

If it is a local variable (such as those you create within a method), you will have to initialize it. So I will say, the default constructor of class X initializes x3, or you can say that, by default it will be initialized as 0.

Upvotes: 1

Related Questions