Skip to content
DevMeme
2261 of 7435
Java Integer Cache Pop Quiz
Languages Post #2516, on Dec 23, 2020 in TG

Java Integer Cache Pop Quiz

Why is this Languages meme funny?

Level 1: The Matching Stickers

This is like two people holding matching numbered stickers. From 0 to 127, the teacher gives them the exact same shared sticker, so they match. At 128, they get two separate stickers with the same number printed on them. The numbers still match, but the stickers are not the same sticker anymore, so the game stops.

Level 2: Same Value, Different Object

Autoboxing is Java's automatic conversion between primitive values like int and wrapper objects like Integer. It is convenient because you can write Integer a = 0; and Java will turn the 0 into an Integer object for you.

The important distinction is value equality versus reference equality. a.equals(b) asks whether two Integer objects represent the same number. a == b asks whether they are literally the same object in memory. Because Java caches small boxed integers, a == b can appear to work for small values and then suddenly fail at 128.

For newer developers, this is one of those subtle bugs that teaches an uncomfortable lesson: code can be wrong even when it looks obvious. If these variables had been declared as int a = 0; int b = 0;, the loop would behave very differently. The meme is funny because the exam hides a runtime detail inside code that looks like basic counting.

Level 3: Boxed Into 128

The teacher: the test isn't that hard

100 points: write below the output of the program:

The joke is that the test looks like a tiny loop, but it is actually a trapdoor into Java's boxed primitive behavior. The code uses Integer, not int, and the loop condition is while(a==b). That single choice turns a beginner-looking exercise into a senior-developer flashback about autoboxing, reference equality, and why language gotchas should come with hazard labels.

In Java, Integer is an object wrapper around an int. The operator == behaves differently depending on what it is comparing. For primitive int values, it compares numeric value. For object references like Integer a and Integer b, it compares whether both variables point to the same object. Java also caches boxed integers in a small required range, commonly -128 through 127, so Integer.valueOf(0) through Integer.valueOf(127) can return shared objects.

That means the loop keeps running while a and b refer to the same cached object. Each ++a and ++b unboxes the current Integer, increments the primitive value, then boxes it again. For 0 through 127, both variables typically receive the same cached object for each value. When they increment to 128, the usual cache no longer applies, so a and b become two distinct Integer objects with the same numeric value. The next a==b is false, the loop exits, and the print statement gives:

The output is 128

The cruel part is that this is technically fair if the class has covered wrapper classes, but emotionally it is a mugging. The caption says the test "isn't that hard" while the actual question punishes anyone who learned == as "equals" without also learning when Java quietly swaps values for objects behind the curtain.

Description

A dark-background meme shows a mock exam: "The teacher: the test isn't that hard" followed by "The test:" and a Java code snippet. The code defines `Integer a = 0; Integer b = 0; while(a==b) { ++a; ++b; }` and then prints `System.out.println("The output is "+a);`, with a 100-point prompt asking for the output. The joke relies on Java autoboxing and `Integer` caching: small boxed integers compare reference-equal via `==`, but once both values become 128 they are usually boxed as separate objects, so the loop exits and prints 128.

Comments

98
Anonymous ★ Top Pick The answer is 128, unless someone tuned `IntegerCache` and turned the exam into a JVM configuration audit.
  1. Anonymous ★ Top Pick

    The answer is 128, unless someone tuned `IntegerCache` and turned the exam into a JVM configuration audit.

  2. @sylfn 5y

    There will be no output

  3. @sylfn 5y

    Because the program never reaches output statement

    1. @illia_sahaidak 5y

      You don’t say?

      1. @bladefistx2 5y

        He's wrong the output is 0. Read the code again or run it yourself

  4. @misesOnWheels 5y

    comparing objects by reference ...

  5. @sylfn 5y

    C++ style...

  6. @sylfn 5y

    Just redefine that operator

  7. @maxgraey 5y

    Output: ⊥

  8. Deleted Account 5y

    if this was c++ you could write whatever and it will count

  9. @KiT_BoPKiT 5y

    писькодроч

  10. @s2504s 5y

    А я чёт тоже недогнал чё за ответ будет, лол

  11. @mahdisml 5y

    output is 0

    1. Deleted Account 5y

      y tho

  12. @s2504s 5y

    Пачиму??

  13. @s2504s 5y

    Переполнение буфера может?

  14. @yevhen_k 5y

    Ноль, потому что сравниваются ссылочные типы на равенство, которое даст false

    1. Deleted Account 5y

      java java

      1. @yevhen_k 5y

        Exactly, bro

        1. Deleted Account 5y

          wait, is that == operator is functionaly useless?

      2. @alexolexo 5y

        Thankfully, I write in Kotlin

    2. @offpeakhours 5y

      є кеш інтів, тому 128

      1. @RiedleroD 5y

        ah bruh. That's a big brain meme if I've ever seen one.

        1. @Almamu 5y

          Indeed

      2. @Almamu 5y

        Dang, and they complain about PHP's quirks? Fml I would not be able to figure that if I had a bug in software like that

        1. Deleted Account 5y

          python has it too!

  15. @s2504s 5y

    Аааааа,

  16. @RiedleroD 5y

    I've seen that meme a couple of times, but I just realized: those are Integers, not ints and since Java compares Objects by reference, not by content, the loop wouldn't start and the output would be 0.

  17. @maxgraey 5y

    Otput will be 128!

    1. Deleted Account 5y

      that's a big number ngl

      1. Deleted Account 5y

        lol

  18. @maxgraey 5y

    https://wiki.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

  19. @CustomIcon 5y

    bruh

    1. Deleted Account 5y

      wait youre here

    2. Deleted Account 5y

      oh you are in comments xd

      1. @CustomIcon 5y

        i know the python way

        1. Deleted Account 5y

          same

  20. Deleted Account 5y

    Hmm

  21. @yevhen_k 5y

    Java, go fuck yourself. I'm going to use python or rust instead

    1. @RiedleroD 5y

      it's the same in python…

      1. @RiedleroD 5y

        well, if you compare by id, that is

    2. Deleted Account 5y

      s/rust/C

    3. Deleted Account 5y

      a = -5 b = -5 while (a := a + 1) is (b := b + 1): pass print(i)

      1. @yevhen_k 5y

        Yeah, but in python you explicitly use reference comparison

        1. @Almamu 5y

          Yeah, it's doesn't shoot you in the feet without warning

        2. Deleted Account 5y

          yes i agree java bad

          1. @CustomIcon 5y

            hey guess what. i learnt nim instead of kotlin. and i dont regret it

            1. Deleted Account 5y

              fuck you

            2. Deleted Account 5y

              kotlin is best

              1. Deleted Account 5y

                jvm tho

                1. Deleted Account 5y

                  Yep

                2. Deleted Account 5y

                  jvm is literally faster than C

                  1. Deleted Account 5y

                    HAHAHAHAHAN'T

                  2. Deleted Account 5y

                    refer to the conversation above

                    1. Deleted Account 5y

                      what, the test code with a and b?

                      1. Deleted Account 5y

                        no, with Slava S.

                        1. Deleted Account 5y

                          what

                          1. Deleted Account 5y

                            if you are not in chat then the post "C++ devs when their thousand line code..."

                            1. Deleted Account 5y

                              oh i'm here

                        2. Deleted Account 5y

                          what's slava s

                  3. Deleted Account 5y

                    https://benchmarksgame-team.pages.debian.net/benchmarksgame/performance/mandelbrot.html

                    1. @RiedleroD 5y

                      lol even node.js is faster

                      1. Deleted Account 5y

                        Lol

                    2. Deleted Account 5y

                      this page literally says you have to read the code to see which are threaded

                      1. Deleted Account 5y

                        And indeed both Java and C programs are multithreaded

                        1. Deleted Account 5y

                          Yes

              2. @Almamu 5y

                PHP POWA

                1. Deleted Account 5y

                  Shut the fuck up...

                  1. @Almamu 5y

                    Just kidding, but C# or C++ all the way

                    1. Deleted Account 5y

                      Oh, still I don't like C# nor C++ but I mean still better than that shitwell

            3. Deleted Account 5y

              They both suck

  22. @bit69tream 5y

    btw this looks completely unlogical

    1. @RiedleroD 5y

      most tests do. ever did a math test? yeah it's the same with programming.

  23. @CustomIcon 5y

    a = 0 b = 0 while a==b: a += 1 b += 1 print ("The output is: {output}".format(output=a))

    1. @RiedleroD 5y

      that'd be infinity

    2. Deleted Account 5y

      no

    3. Deleted Account 5y

      a = -5 b = -5 while (a := a + 1) is (b := b + 1): pass print(a, b)

      1. @CustomIcon 5y

        walrus i must hate

      2. @RiedleroD 5y

        a bit simpler would be: a=0 b=0 while a is b: a+=1 b+=1 print(a,b) also, keep in mind that the walrus operator is new in 3.8, and therefore incompatible with most python installations. 3.6 is usually the target version.

        1. Deleted Account 5y

          fuck 3.6 it doesn't even support f strings

          1. @RiedleroD 5y

            yes it does…

            1. Deleted Account 5y

              does it? i don't remember that

              1. @RiedleroD 5y

                I think 3.6 is the version where they were first introduced.

                1. Deleted Account 5y

                  i thought it was 3.7

                  1. @RiedleroD 5y

                    3.7 was the asyncio update

  24. Deleted Account 5y

    Language: ruby Source: a = b = 0 while a == b a += 1 b += 1 end puts(a) Errors: Kill signal (SIGKILL)

  25. @yevhen_k 5y

    Numpy is the fastest language 😂

  26. @panzer_maus 5y

    128 :)

    1. @mahdisml 5y

      nice ! my answer was right

    2. Red Я. 5y

      Old school rules)

  27. Deleted Account 5y

    Primer comentario en español

  28. @panzer_maus 5y

    This is because under 127 all Integers have same reference

  29. @Withouthatewithoutfear 5y

    To will get a output when it adventually crashes

    1. @bladefistx2 5y

      It will always output 0

      1. Deleted Account 5y

        it will output 128

        1. @bladefistx2 5y

          Lol i read while a=b

          1. Deleted Account 5y

            i thought i was going insane, but you just deleted that message

  30. @Cuwano 5y

    But why 128?

Use J and K for navigation