Java - What is the output: initializes final variable in constructor?

Question

What is the output of the following code?

class Test {

  private final int y;

  public Test() {
    y = 10; 
    System.out.println(y);
  }

  public Test(int z) {
    y = z;
    System.out.println(y);
  }

}

public class Main {

  public static void main(String[] args) {
    new Test();
  }
}


Click to view the answer

10

Note

The code initializes the blank final instance variable y in both constructors.

When an object of the class is created, it will use one of the two constructors, not both.

Therefore, for each object of the class, y is initialized only once.

Related Quiz