Which line of code, inserted at line p1, causes the application to print 5?
package mypkg; // w w w.jav a 2 s .co m public class Main { private int v = 1; protected boolean outside; public Main() { // p1 outside = true; } public Main(int v) { this.v = outside ? v : v+1; } public static void main(String[] bounce) { System.out.print(new Main().v); } }
A.
All of the lines compile but they produce various different results.
The default initialization of a boolean instance variable is false, making outside false at line p1.
this(4) will cause v to be set to 5, while this(5) will cause v to be set to 6.
Since 5 is the number we are looking for, Option A is correct, and Option C is incorrect.
Option B is incorrect.
While the statement does create a new instance of Main, with v having a value of 5, that instance is nested and the value of v does not affect the surrounding instance of Main that the constructor was called in.
Option D is also incorrect.
The value assigned to v is 4, not the target 5.