Choosing how to earn college credit? CLEP vs AP guide
| preferred AP College board partner for AP classes
medium Solved by 6 students

Assignment Versus Equality in a Conditional

Mark
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Total Time
Score
#1171662811 0m 14s 86
#2barkern19511 0m 17s 83
#3lsj0803092212 0m 08s 82
#4srivastavarishit63511 0m 23s 77
#5Potter1611 0m 30s 70
#6patrickmeijer00912 0m 58s 32
Items per page:
10
1 – 6 of 6
No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Instagram: @_apfive_|Privacy Policy|