Monday 11 February 2013

4. What will be the result of executing the following code?

4. What will be the result of executing the following code?
1.    boolean a = true;
2.    boolean b = false;
3.    boolean c = true;
4.    if (a == true)
5.    if (b == true)
6.    if (c == true)          System.out.println("Some things are true in this world");
7.    else                    System.out.println("Nothing is true in this world!");
8.    else if (a && (b = c))  System.out.println("It's too confusing to tell what is true and what is false");
9.    else                    System.out.println("Hey this won't compile");

Choices:
a.  The code won't compile
b. "Some things are true in this world" will be printed
c. "Hey this won't compile" will be printed
d. None of these


Answers:
D is correct.
This is a very good question to test the concepts of execution flow in case of if conditions.
The rule for attaching else statements with if conditions is the same as attaching close brackets with open brackets.
A close bracket attaches with the closest open bracket, which is not already closed. Similarly an else statement attaches with the closest if statement, which doesn't have an else statement already, attached to it.

So the else statement at line 7 attaches to the if statement at line 6.
The else statement at line 8 attaches to the if statement at line 5.
The else statement at line 9 attaches to the if statement at line 8.
Now let's look at the execution.

At line 4 since a is equal to true the execution falls to line 5.
At line 5 since b is not true the execution goes to the corresponding else statement at line 8.
Now it evaluates the condition inside the if statement.
Please note here that an assignment statement also has a value equal to the value being assigned,
hence (b = c) evaluates to true and subsequently a && (b = c) evaluates to true and "It's too confusing to tell what is true and what is false" will be printed.
Hence the correct answer is choice D.

X

No comments:

Post a Comment