Course contentsShow
← Java
Lesson 113 of 2,8703. Operators and ExpressionsFree lesson

Common Pitfalls: Assignment vs Equality

Recognize the critical difference between = (assignment) and == (comparison) to avoid logic errors.

Common Pitfalls: Assignment vs Equality

What you'll learn: You'll discover why mixing up = and == is one of the most frequent mistakes beginners make — and how to avoid it.

The Problem

Java uses two operators that look similar but do completely different things:

  • = (single equals) — the assignment operator that stores a value in a variable
  • == (double equals) — the equality comparison operator that checks if two values are the same

Confusing these two causes logic errors that can be tricky to spot.

How the Mistake Happens

Imagine you want to check if a number equals 5:

int x = 10;

if (x = 5) {  // WRONG! This assigns 5 to x
    System.out.println("x is 5");
}

What you intended: Check if x equals 5
What actually happened: You assigned 5 to x, overwriting its original value

The correct version uses ==:

int x = 10;

if (x == 5) {  // Correct: compares x to 5
    System.out.println("x is 5");
}

Why This Is Dangerous

With int variables, Java will often catch this mistake because x = 5 produces an int, not a boolean, causing a compilation error. But with boolean variables, the code compiles and silently does the wrong thing:

boolean ready = false;

if (ready = true) {  // Assigns true to ready, always executes!
    System.out.println("Ready!");
}

This always prints "Ready!" because the assignment itself evaluates to true.

The Simple Rule

Think of it this way: one equals gives, two equals asks.

Key Takeaway: Always use = to assign values and == to compare them. Double-check your conditions to ensure you're comparing, not accidentally reassigning!