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);
}
}
- A.
A
- B.
AB
- C.
B
- 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 ".