Question:
Consider the following code snippet:
int num = 10;
String str = "Hello";
if (num >= 0) {
if (str.length() > 5) {
System.out.println("Condition 1");
} else {
System.out.println("Condition 2");
}
} else if (str.equals("Goodbye")) {
System.out.println("Condition 3");
} else {
System.out.println("Condition 4");
}
What will be the output of the above code if it is executed?
A) Condition 1
B) Condition 2
C) Condition 3
D) Condition 4
E) None of the above
Explanation:
The control flow of the code can be analyzed step-by-step:
The variable num
has a value of 10, which is greater than or equal to 0. So, the code enters the first if
statement.
Inside the first if
statement, the condition str.length() > 5
is checked. The length of the string str
is 5, which is not greater than 5. Hence, the code executes the else
block and prints "Condition 2".
Since the code has executed the else
block in the first if
statement, it skips the remaining else if
and else
blocks. Therefore, the output of the code will be "Condition 2".
Hence, the correct answer is B) Condition 2.
Note: It is important to carefully analyze the control flow of the code to determine the correct output.