Think Dream Create Inovate

Thursday, June 9, 2011

Flow Control in Java

1.public void foo( boolean a, boolean b)
{
if( a )
{
System.out.println("A"); /* Line 5 */
}
else if(a && b) /* Line 7 */
{
System.out.println( "A && B");
}
else /* Line 11 */
{
if ( !b )
{
System.out.println( "notB") ;
}
else
{
System.out.println( "ELSE" ) ;
}
}
}

A. If a is true and b is true then the output is "A && B"
B. If a is true and b is false then the output is "notB"
C. If a is false and b is true then the output is "ELSE"
D. If a is false and b is false then the output is "ELSE"
Answer & Explanation

Answer: Option C

Explanation:

Option C is correct. The output is "ELSE". Only when a is false do the output lines after 11 get some chance of executing.

Option A is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed. The condition at line 7 will never be evaluated (when a is true it will always be trapped by the line 12 condition) therefore the output will never be "A && B".

Option B is wrong. The output is "A". When a is true, irrespective of the value of b, only the line 5 output will be executed.

Option D is wrong. The output is "notB".

2. public void test(int x)
{
int odd = 1;
if(odd) /* Line 4 */
{
System.out.println("odd");
}
else
{
System.out.println("even");
}
}

Which statement is true?

A. Compilation fails.
B. "odd" will always be output.
C. "even" will always be output.
D. "odd" will be output for odd values of x, and "even" for even values.
Answer & Explanation

Answer: Option A

Explanation:

The compiler will complain because of incompatible types (line 4), the if expects a boolean but it gets an integer.

1 comment: