Course contentsShow
← Java
Lesson 141 of 2,8704. Control Flow StructuresFree lesson

Common Pitfalls: Assignment vs Comparison

Recognize the critical difference between = (assignment) and == (comparison) in conditions and how to avoid this bug.

Common Pitfalls: Assignment vs Comparison

You'll learn how to avoid one of the most frustrating beginner bugs: accidentally assigning a value in a condition instead of comparing.

The Critical Difference

In Java, = (single equals) means assignment — you're putting a value into a variable. But == (double equals) means comparison — you're asking "are these equal?" In conditions, you almost always want comparison, but it's easy to type just one = by mistake.

Why This Bug Is Dangerous

Consider this erroneous code:

int age = 25;

if (age = 18) {  // WRONG! This assigns 18 to age
    System.out.println("You are 18");
}

What happens: This code tries to assign 18 to age, not compare them. Worse, the assignment doesn't produce a boolean result, so this won't even compile! Java saves you here because 18 is an int, not a boolean.

However, with boolean variables, the bug does compile:

boolean isReady = true;

if (isReady = false) {  // WRONG! This sets isReady to false
    System.out.println("Ready!");
}

This compiles and runs, but the condition always assigns false to isReady and then evaluates that false, so the print never executes. The original value of isReady is lost!

The Correct Way

Always use == for comparison in conditions:

if (age == 18) {  // Correct: compares age to 18
    System.out.println("You are 18");
}

if (isReady == true) {  // Correct, though (isReady) is cleaner
    System.out.println("Ready!");
}

Key Takeaway: Use == to compare values in conditions, never =. The single equals is for assignment only. Watch especially carefully with boolean variables where assignment bugs compile silently!