Assignment Versus Equality in a Conditional
The following code segment is intended to produce different outputs based on the value of the boolean variable flag. However, the code always prints Flag is true when executed. Which statement best explains this logical error?
public class ConditionBug {
public static void main(String[] args) {
boolean flag = false;
if (flag = true) {
System.out.println("Flag is true");
} else {
System.out.println("Flag is false");
}
}
}
A
The assignment operator ‘=’ is used in the if condition instead of the equality operator ‘==’, causing ‘flag’ to be set to true.
B
The code uses an illegal syntax in the if condition.
C
The print statements are reversed, leading to the wrong output message.
D
The boolean variable ‘flag’ was supposed to be initialized as true instead of false.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | 1716628 | 1 | 1 | 0m 14s | 86 |
| #2 | barkern195 | 1 | 1 | 0m 17s | 83 |
| #3 | lsj08030922 | 1 | 2 | 0m 08s | 82 |
| #4 | srivastavarishit635 | 1 | 1 | 0m 23s | 77 |
| #5 | Potter16 | 1 | 1 | 0m 30s | 70 |
| #6 | patrickmeijer009 | 1 | 2 | 0m 58s | 32 |
Items per page:
10
1 – 6 of 6
