What will be the output of the following code? public class Test { Test() {…

2025

What will be the output of the following code?

public class Test {
Test() {
System.out.print("A ");
}
Test(int x) {
this();
System.out.print("B ");
}
public static void main(String[] args) {
new Test(5);
}
}

  1. A.

    A

  2. B.

    AB

  3. C.

    B

  4. D.

    Compilation error

Attempted by 63 students.

Show answer & explanation

Correct answer: B

In this Java program, the constructor Test(int x) calls the default constructor using this();.

Execution steps:

new Test(5); calls the constructor Test(int x).
Inside Test(int x), this(); invokes the default constructor Test().
The default constructor prints "A ".
Control returns to Test(int x), which then prints "B ".

Explore the full course: Rssb Senior Computer Instructor