Skip to content
DevMeme
4508 of 7435
Only 5 of 1000 can trace this Java assignment-precedence brain-twister
Languages Post #4947, on Oct 20, 2022 in TG

Only 5 of 1000 can trace this Java assignment-precedence brain-twister

Why is this Languages meme funny?

Level 1: Magic Trick in Code

Imagine you have five boxes with numbers in them. This code does a sneaky magic trick with those numbers. It changes some of the numbers one by one, but it has a rule: if one step doesn’t go as planned, it skips doing some of the later steps. In the end, a few of the boxes have new numbers and the rest stay the same. The funny part is that most people get confused about which boxes changed and which didn’t – it’s like watching a magician shuffle cups and trying to guess where the ball is. Only a handful of people can follow every hidden swap and get the answer right, which is exactly why this puzzle makes programmers smile (and groan a little)!

Level 2: Assignment vs Equality

This code is a classic trick question mixing up the assignment and equality operators in Java. Here’s what’s happening in simpler terms:

  • = (assignment) vs == (equality): In Java, a single equals sign = sets a variable’s value, whereas a double equals == checks if two values are the same. For example, a = 1 will change the value of a to 1, but a == 1 asks “is a equal to 1?”. In this code, expressions like (a=1) == 1 are doing both: first assigning 1 to a, then comparing the result with 1. That’s very unusual to see inside a while condition – normally you’d just compare variables to values, not change them at the same time! This little trick is easy to miss if you glance quickly, since (a=1)==1 looks somewhat like a comparison at first.

  • The while loop condition: A while loop keeps running its body as long as the condition in parentheses is true. The condition here is:

    (a=1)==1 && (b=2)==3 && (c=3)==3 || (d=4)==4 || (e=5)==7
    

    It’s using both AND (&&) and OR (||) operators:

    • && means “this AND that both need to be true.”
    • || means “this OR that can be true (only one needs to pass).”

    Operator precedence: In Java, && has a higher priority than ||. That means the three && parts are evaluated together first, then the || parts are considered. So it's as if the condition was grouped like:

    // AND group first, then ORs:
    ((a=1)==1 && (b=2)==3 && (c=3)==3) 
       || (d=4)==4 
       || (e=5)==7
    

    The program will evaluate this from left to right.

  • Execution step-by-step: Let’s trace through the condition with the initial values a=9, b=4, c=7, d=1, e=3:

    1. (a = 1) == 1: Set a to 1 (it was 9). Now check if a equals 1. Yes it does (1 == 1 is true).
    2. (b = 2) == 3: Since the previous part was true, we continue. Set b to 2 (it was 4). Now check if b equals 3. 2 == 3 is false.
    3. (Skip c part): The moment one part of an && is false, the rest of that && group is skipped. So because the b check failed, the code does not execute (c=3)==3 at all. That means c stays 7 (its original value).
    4. Now we move on to the || parts. So far the left side (the big AND group) is false, but with OR, we still have a chance for the whole condition to be true if one of the OR parts succeeds.
    5. (d = 4) == 4: Set d to 4 (it was 1). Check if d equals 4. Yes, 4 == 4 is true.
    6. (Skip e part): In an || chain, once something is true, Java skips the rest because it already knows the whole condition is true. So now that the d part is true, the program doesn’t even evaluate (e=5)==7. Thus e stays 3.

    After these steps, the while condition has evaluated to true (thanks to the d part). At this point:

    • a has become 1,
    • b has become 2,
    • c is still 7 (unchanged),
    • d is now 4,
    • e is still 3.

    So inside the loop, when System.out.println runs, it will print 1 2 7 4 3. That matches the meme’s answer. The break; in the loop then stops any further looping (otherwise, since the condition would likely stay true, it might repeat forever).

  • Why it’s tricky: This is tricky because it abuses the way Java evaluates expressions. The code hides assignments in what looks like comparisons, and relies on the short-circuit rules of && and || to skip some of them. If you didn’t know about these rules, you might expect all the variables to change or none of them to change, and you’d guess the output wrong. It’s also a lot to keep track of in your head: five variables changing or not changing based on multiple conditions. No wonder only a few students got it right!

  • Takeaway: This puzzle is a reminder of how important understanding the basics is. Know the difference between = and ==. Remember that in Java, certain operators are checked before others unless you use parentheses. And be aware that sometimes parts of a boolean expression won’t run at all if Java already knows the result from earlier parts. It’s a fun example of Java’s control flow quirks with logical operators, but in real life you should avoid writing code that’s this confusing.

Level 3: Precedence Predicament

This Java snippet is a masterclass in hidden assignments and operator precedence – a puzzle so sneaky that apparently only 5 out of 1000 students got it right. It's the kind of trick you'd encounter in a CodingChallenge or a high-pressure interview, merging CS fundamentals with "gotcha" humor. Let's unpack why this one-liner while condition is such a brain-twister and how it prints 1 2 7 4 3 despite the initial values (9 4 7 1 3):

  • Assignment as an expression: In Java (just like in C), the assignment operator = doesn't just set a value; it returns that value as an expression result. This means you can write something like (a = 1) inside a condition, and it evaluates to 1 (while also setting a). Many newbies mix up assignment and equality by accident, but here it's used intentionally. The code (a=1)==1 first assigns a to 1, then compares that result to 1. Sneaky, right?

  • Operator precedence and grouping: Java's logical && (AND) has higher precedence than || (OR). So the condition:

    (a=1)==1 && (b=2)==3 && (c=3)==3 || (d=4)==4 || (e=5)==7
    

    is effectively grouped as:

    // && chain is evaluated first, then ||:
    if ( ((a=1)==1 && (b=2)==3 && (c=3)==3) || ((d=4)==4) || ((e=5)==7) ) { ... }
    

    All three && parts must be true to satisfy the left group before the ORs even matter.

  • Short-circuit evaluation: Java uses short-circuit logic for && and ||. This means:

    1. For an && chain, if any part is false, Java stops evaluating the rest (because false AND anything = false).
    2. For an || chain, if any part is true, it stops (since true OR anything = true).

    Now watch the condition execute in order:

    1. (a=1)==1 – The code assigns a a new value 1 (was 9) and checks if it's equal to 1. Yes, 1 == 1 is true. So far so good, the first part of the && chain passed.
    2. (b=2)==3 – Next, it assigns b the value 2 (was 4) and checks 2 == 3. That's false. Uh-oh, we've hit a false in an && sequence.
    3. Because the b part failed, the entire (a && b && c) group is now false. Short-circuit kicks in: Java skips evaluating (c=3)==3 entirely. This is crucial – c remains unchanged (still 7, since we never got to assign it).
    4. Now the condition so far is false for the left side of the ||. But we have || (d=4)==4 || (e=5)==7 to check. With OR, since the left group was false, we proceed.
    5. (d=4)==4 – It assigns d the value 4 (was 1) and checks 4 == 4, which is true. Bingo! We found a true condition in the OR chain.
    6. Because an OR condition succeeded at d, short-circuit stops the rest of the OR checks. We do not evaluate (e=5)==7 at all. So e stays 3 (unchanged).
  • Net effect: The while loop's condition ends up true (thanks to the d part). At this moment, the variables have been mutated in a staggered way:

    • a is now 1 (changed),
    • b is 2 (changed),
    • c is still 7 (unchanged, short-circuited before assignment),
    • d is now 4 (changed),
    • e is still 3 (unchanged, short-circuited).

    When the loop executes its body, System.out.println(a + " " + b + " " + c + " " + d + " " + e); outputs 1 2 7 4 3 – the exact mix of new and old values. Immediately after printing, the code hits break;, exiting the loop.

  • Why is this funny (or scary)? It's a perfect storm of LanguageQuirks. Few students expect a while condition to perform multiple assignments and comparisons in one line. It's almost like a logic puzzle smuggled into code form. The humor is in watching even good programmers go "Wait, how did c end up 7?!" as they untangle the steps. This kind of crazy condition is more common as an InterviewHumor trick question or a competition puzzle than in real production code (thankfully!).

  • Lessons learned: This meme highlights fundamental Java CS_Fundamentals:

    • Always distinguish assignment (=) from equality (==). Here they put an assignment right next to a comparison to trip you up.
    • Remember operator precedence: && binds tighter than ||, which dictated how the condition was interpreted.
    • Understand short-circuit evaluation: it can skip parts of your code. (In debugging, if you ever wonder "why didn't this variable update?", check if a short-circuit prevented that code from running!)

For seasoned developers, this snippet triggers a mix of admiration and horror. Admiration for the clever use of Java's rules (it’s a neat party trick in code form!), and horror because debugging something like this in real life would be a nightmare. It's a great reminder that just because you can do something in code doesn't mean you should – unless your goal is specifically to stump students or colleagues.

Description

The image has a black background with white text. The top caption reads, "Uni stats says only 5 students out of 1k able to answer right:". Below that, a white code panel shows the exact Java snippet: public static void main(String[] args) { int a=9,b=4,c=7,d=1,e=3; while ((a=1)==1 && (b=2)==3 && (c=3)==3 || (d=4)==4 || (e=5)==7) { System.out.println(a + " " + b + " " + c + " " + d + " " + e); break; } } The joke relies on hidden assignments inside the while-condition and Java's operator-precedence/short-circuit rules, causing the loop to print "1 2 7 4 3" despite the initial values. It pokes fun at how few students (or interviewees) remember that `=` returns a value, `&&` binds tighter than `||`, and evaluation stops once an `&&` chain hits false

Comments

55
Anonymous ★ Top Pick Seeing while((a=1)==1 && (b=2)==3 …) in a code review is that special moment you realize operator precedence isn’t the bug - someone just packed side-effects, job security, and a subtle “I quit” into one boolean
  1. Anonymous ★ Top Pick

    Seeing while((a=1)==1 && (b=2)==3 …) in a code review is that special moment you realize operator precedence isn’t the bug - someone just packed side-effects, job security, and a subtle “I quit” into one boolean

  2. Anonymous

    After 20 years of code reviews, I've learned that the difference between = and == in conditionals is what separates those who debug production incidents at 3am from those who cause them. Though honestly, any codebase that makes it past review with assignments in conditionals probably has bigger architectural problems than operator confusion

  3. Anonymous

    Ah yes, the classic 'assignment masquerading as comparison' interview hazing ritual. This is the kind of code that makes you appreciate why modern linters scream at you for assignments in conditionals. The real answer? Only 5 out of 1000 students got it right because the other 995 had already learned to write maintainable code and refused to engage with this production-ready nightmare on principle. If you unironically write conditions like this, your PR reviews must be absolutely *chef's kiss* brutal

  4. Anonymous

    1 & 2 = 0: bitwise AND's polite way of saying 'loop over, no println invited'

  5. Anonymous

    Prints 1 2 7 4 3 exactly once - also known as the mandatory code‑review where we enable a linter and ban assignment in conditionals forever

  6. Anonymous

    It prints “1 2 7 4 3” once - short-circuit assignments set a,b,d and skip c,e; academia calls it a clever exam question, production calls it a postmortem

  7. @sylfn 3y

    1 2 3 4 5 ?

  8. @cthulhu_dev 3y

    1 2 3 4 3

  9. @pointan 3y

    1 2 7 4 3

  10. @affirvega 3y

    Nothing

  11. @grandpa_the_kid 3y

    5 is assigned to e and then it is compared to 7, so how can it go into the while body?

    1. @CCZeroOne 3y

      there's OR

  12. Vitalik 3y

    1 2 7 4 3

  13. @trainzman 3y

    Should it even show anything

    1. @callofvoid0 3y

      doesn't that continue to after or ?

      1. @trainzman 3y

        https://en.wikipedia.org/wiki/Short-circuit_evaluation

        1. @trainzman 3y

          Then, If we account both this

    2. @M4lenov 3y

      No this part makes the program not execute the rest of monominal (c=3) and skips to the d=4 part

      1. @trainzman 3y

        I talked about it lower

    3. @scout_ca11sign 3y

      Yes && Has bigger priority than || Think of it as multiplying first and summing later a*b*c + d + e _ a*b*c = 0 d = 1 e = 0 _ 0 + 1 +0 = 1

  14. @Similacrest 3y

    1 2 3 4 3

  15. @mold_in 3y

    6 9 1 4 8 8

  16. @lab0rat 3y

    1 2 7 4 3

  17. @grandpa_the_kid 3y

    oh, jeez, realy)

  18. @CCZeroOne 3y

    )

  19. @realVitShadyTV 3y

    1 2 7 4 3

  20. @callofvoid0 3y

    12743

  21. @CCZeroOne 3y

    it's probably 12743, but I can also see it being 12343, if it's a trick question, and the third one gets evaluated, cuz there's something after it

  22. @trainzman 3y

    I guess Java uses it

  23. @trainzman 3y

    It won't print anything anyway

  24. @trainzman 3y

    Because && has less priority than || iirc

    1. @sylfn 3y

      AND has greater priority than OR

      1. @trainzman 3y

        And this

    2. @callofvoid0 3y

      I thought it reads from left to right without propority

      1. @trainzman 3y

        It doesn't

  25. @Samurhai 3y

    12743?

  26. @trainzman 3y

    It should give 12743

  27. @trainzman 3y

    They always have different priorities

  28. @CCZeroOne 3y

    alright it is 12743

  29. @CCZeroOne 3y

    I checked

  30. Егор 3y

    it’s 1 2 7 4 3 obviously, but RIGHT answer is «i don’t care»

  31. @callofvoid0 3y

    seems like whole left hand part of first || is counted as a block

    1. @beton_kruglosu_totchno 3y

      no it's not

    2. Егор 3y

      it stops processing ANDs when finds first false and stops processing ORs when it finds first true

      1. @callofvoid0 3y

        ah thanks

      2. @callofvoid0 3y

        resulted exactly as this

    3. @beton_kruglosu_totchno 3y

      AND and OR have same precedence

  32. @callofvoid0 3y

    let me change position of and,or and see what happens

  33. @DavidGarciaCat 3y

    infinite loop?

    1. @dst212 3y

      break; doesn't agree

      1. @DavidGarciaCat 3y

        Yeah, I ran a quick investigation later and I know now my both guessings were wrong

  34. @DavidGarciaCat 3y

    or maybe syntax error?

  35. dev_meme 3y

    The real answer to this is refactoring 😂👀

  36. @realbond007 3y

    a=1 (first assignment) | 1==1 : true, continue condition evaluation b=2 (second assignment) | 2==3 : false, short circuit break (AND FALSE operation), therefore all following && will be ignored c=7 (initial value remains - see comment above) d=4 (third assignment) | 4==4 : true, short circuit break (OR TRUE operation), therefore all following || will be ignored e=3 (initial value remains - see comment above) therefore 1 2 7 4 3 🤓

  37. @Iliya_malecki 3y

    1 2 7 4 5 piss easy

Use J and K for navigation