Java traps · Chapter 2 of 16

== on boxed Integers

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Everyday traps
  • 3 tasks
  • Java
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Boxing calls Integer.valueOf, which keeps a cache of the objects for -128 to 127. Box 72 twice and you get the same cached object, so == happens to be true. Box 1100 twice and you get two new objects:

Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
true
false
true

So every test with small counts passes, and nothing throws: the comparison is just wrong for big numbers.

The fix is to compare the numbers. equals does, but it throws when the left side is null, and a map gives null for a key it does not have. Objects.equals(a, b) handles that. Unboxing by hand with intValue() throws on null too (the next case is about that trap):

System.out.println(Objects.equals(BOOKED.get("12627"), SEATS.get("12627")));
System.out.println(Objects.equals(BOOKED.get("12658"), SEATS.get("12658")));
System.out.println(BOOKED.get("12658").intValue() == SEATS.get("12658"));
true
false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
	at Fix.main(Fix.java:11)

(BOOKED has no train 12658; SEATS has 980 seats for it.)

The lesson

By the end of this case

You can tell == on boxed numbers from its symptoms (small values fine, big ones wrong), make it happen on purpose with two counts boxed on their own, fix it with a null-safe equals, and guard it with a test that uses a number above 127.

The ticket

TC-515: The night count flags every big item. Assigned to you by Kabir. Priority: high. Since: the new stock check went live on Thursday.

Ravi, in the operations group at 11:55 pm: "Arjun at NDLS counted 500 cups, the till expects 500 cups, and the night check says cups do not match. Same with milk and sugar sachets. Bun maska and samosa are never flagged. Every counter is recounting the big items by hand, and that is an hour gone every night."

The stock check's log for NDLS last night:

23:41:07  night-count  stock NDLS: cups counted 500, expected 500
23:41:07  night-count  stock NDLS: milk counted 240, expected 240
23:41:07  night-count  stock NDLS: sugar sachets counted 1200, expected 1200

Kabir: "The old check compared two int columns. Thursday's version keeps the counts in a Map<String, Integer>, so a counter can count any item. Look at which items get flagged: 36 and 48 pass, 240 and 500 do not. The size of a number should never matter to an equality check. Reproduce it, fix it, and make sure it never comes back. You are in StockCheck.java."

A boxed number is an object

A Map cannot hold an int, so Java boxes each number into an Integer object when you put it in. Two Integers compared with == or != are compared as objects: the same object?, not the same number. Seat counts for a coach and for a whole train, in a small program run with java Seats.java:

Map<String, Integer> booked = new HashMap<>();
Map<String, Integer> seats = new HashMap<>();
booked.put("B2", 72);
seats.put("B2", 72);
booked.put("12627", 1100);
seats.put("12627", 1100);
System.out.println(booked.get("B2") == seats.get("B2"));
System.out.println(booked.get("12627") == seats.get("12627"));
System.out.println(booked.get("12627").equals(seats.get("12627")));
true
false
true

Making it happen on purpose

Your reproduce() counts cups at 500 and expects 500, with each count boxed on its own, as the till does when it reads two sheets. One Integer put in both maps is one object, and != would say they match. The check runs it beside the original StockCheck.java (["cups"]) and beside a fixed one ([]).

A test that would have caught it

The numbers you pick decide whether a test can see this bug. A test with samosa at 48 passes on the bug. Use a count above 127, and an item nobody counted, which a hurried fix turns into a crash. A test that throws an exception fails, so you need no try for that.

Your turn

Three tasks, one file each. In Repro.java, flag cups that match on purpose (cd chapters/02-integer-cache, then run-app). In StockCheck.java, fix the comparison. In StockCheckTest.java, write the guard (run-app test): the check runs it beside the original code, the fix and a wrong fix that unboxes with intValue(). Then answer Kabir's interview question at the bottom of the case.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    Repro.java: cups that match and still get flagged

    Write reproduce() in Repro.java. Make two maps of item to count, one counted and one expected, each with cups at 500, boxing each count on its own (for example Integer.valueOf of the text "500" for each map, not one Integer shared by both). Call StockCheck.mismatches with any station and the two maps, and return the list it gives back.

    The check runs your reproduce() twice: beside the original StockCheck.java it must return ["cups"] (500 and 500 flagged as different), and beside a fixed StockCheck.java it must return []. So it must really count cups and call mismatches. No real waiting and no reading input: reproduce() must finish within 3 seconds.

  2. Task 2

    StockCheck.java: a matching count is not a mismatch

    Fix mismatches(station, counted, expected) in StockCheck.java so that it compares the counts as numbers, however big: an item counted the same as expected is not a mismatch, a different number is, and an item in expected that nobody counted (no entry in counted) is a mismatch without an exception. It looks only at the items in expected and gives the mismatches A to Z.

    Keep its log lines as they are, one per mismatch: stock <station>: <item> counted <n>, expected <m>, and stock <station>: <item> counted nothing, expected <m> for an item nobody counted. The check uses its own stations and items and boxes every count at run time, small and big (127, 128, 500, 1200), and a fix that throws on a missing count is as wrong as the bug.

  3. Task 3

    StockCheckTest.java: a test that would have caught it

    Write a JUnit test class, StockCheckTest.java, that would have caught this bug before it reached the stations. The check runs your file three times: beside the original StockCheck.java, where at least one test must fail; beside the fixed StockCheck.java, where every test must pass; and beside a wrong fix that compares counted.get(item).intValue() with the expected count, where at least one test must fail.

    So test both sides: an item whose count is above 127 and matches is not a mismatch, and an item nobody counted is a mismatch, without an exception. No real waiting: each test must finish within 3 seconds.

What you will learn

  • Repro.java: cups that match and still get flagged
  • StockCheck.java: a matching count is not a mismatch
  • StockCheckTest.java: a test that would have caught it

More in Everyday traps

Build "== on boxed Integers" yourself

Tapri Counter runs on Java, and Kabir, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.