Skip to content
Exercises · Q6

Q.What is the difference between the = operator and the == operator? Give an example where confusing them causes a bug.

ChseodishaTextbookSubjectiveImportance★★★★★est
46% · 6/13 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

= — assignment. This operator stores the value on its right into the variable on its left. It does not compare anything:

int x;
x = 5;      // x now holds 5

== — comparison. This relational operator checks whether two values are equal and produces a boolean result (true or false):

boolean same = (x == 5);   // same is true

Where confusing them bites. Conditions expect a boolean. Suppose you mean to test whether x equals 5:

if (x == 5) {            // correct: tests equality
    System.out.println("five");
}

If you accidentally write a single =:

if (x = 5) { ... }       // ERROR in Java
``` …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.