AP Computer Science Exam Question:
public class ControlFlowQuestion {
public static void main(String[] args) {
boolean condition1 = true;
boolean condition2 = false;
int number = 5;
// Perform control flow operations using if-else statements
if (condition1) {
System.out.println("Condition 1 is true.");
} else if (condition2) {
System.out.println("Condition 2 is true.");
} else {
System.out.println("Neither condition is true.");
}
// Perform control flow operation using switch statement
switch (number) {
case 1:
System.out.println("The number is 1.");
break;
case 2:
System.out.println("The number is 2.");
break;
case 3:
System.out.println("The number is 3.");
break;
default:
System.out.println("The number is not 1, 2, or 3.");
break;
}
}
}
Explain the output of the code above, step-by-step.
Answer with Explanation:
The provided code demonstrates control flow operations using if-else and switch statements. Let's go through the code step-by-step to understand the output:
Three variables are declared and initialized:
condition1
is a boolean variable initialized as true
.condition2
is a boolean variable initialized as false
.number
is an integer variable initialized as 5
.The if-else statement checks condition1
. Since condition1
is true, the code inside the if block executes and prints "Condition 1 is true."
to the console. The else if condition is skipped since condition1
is true.
The switch statement checks the value of number
. The switch expression is 5
. Since no case matches the value 5
, the default case block executes and prints "The number is not 1, 2, or 3."
to the console.
Therefore, the output of the code will be:
Condition 1 is true.
The number is not 1, 2, or 3.
This is because condition1
is true and number
is not 1, 2, or 3.