MCQs
What will be the output of the program?
public class Test
{
public static int y;
public static void foo(int x)
{
System.out.print("foo ");
y = x;
}
public static int bar(int z)
{
System.out.print("bar ");
return y = z;
}
public static void main(String [] args )
{
int t = 0;
assert t > 0 : bar(7);
assert t > 1 : foo(8); /* Line 18 */
System.out.println("done ");
}
}
The foo() method returns void. It is a perfectly acceptable method, but because it returns void
it cannot be used in an assert statement, so line 18 will not compile.
Option D is correct. Compilation fails because of an unreachable statement at line 14.
It is a compile-time error if a statement cannot be executed because it is unreachable.
The question is now, why is line 20 unreachable? If it is because of the assert then
surely line 6 would also be unreachable. The answer must be something other than assert.
Examine the following:
A while statement can complete normally if and only if at least one of the following is true:
- The while statement is reachable and the condition expression is not a constant expression
with value true.
-There is a reachable break statement that exits the while statement.
The while statement at line 11 is infinite and there is no break statement therefore line 14 is
unreachable. You can test this with the following code:
public class Test80
{
public void foo()
{
assert false;
assert false;
}
public void bar()
{
while(true)
{
assert false;
break;
}
assert false;
}
}