Java traps · Chapter 3 of 16
Auto-unboxing null
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
- In the all labs plan
The first 2 chapters of Java traps are free. This one comes with the all labs plan.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
Repro.java: a new passenger's balance that crashes
Write reproduce() in Repro.java. Make a map of phone to points with one passenger in it (say 98450 12345 with 12 points), and ask Points.balance for a phone that is not in the map, a passenger who has never earned points. Return the balance as a String (String.valueOf), or, if balance throws, the simple name of the exception you caught (getClass().getSimpleName()).
The check runs your reproduce() twice: beside the original Points.java it must return "NullPointerException", and beside a fixed Points.java it must return "0". So it must really ask for an unknown phone's balance. No real waiting and no reading input: reproduce() must finish within 3 seconds.
- Task 2
Points.java: a new passenger's balance is 0
Fix balance(balances, phone) in Points.java so that a phone with points gets its points, a phone that is not in the map gets 0 without an exception, no phone (null, a cash bill) gets 0, and a phone stored with 0 gets 0. balance only reads the map. earn(balances, phone, billAmount) must work for a passenger's first bill too: it adds 1 point for every ₹10 (rounded down) to the phone's balance, stores it and returns it.
Keep earn's log line as it is: pass <phone>: +<earned> points, balance <total>. The check uses its own phones and maps and asks for phones that are not in the map at all.
- Task 3
PointsTest.java: a test that would have caught it
Write a JUnit test class, PointsTest.java, that would have caught this bug before it reached the stations. The check runs your file twice: beside the original Points.java, where at least one test must fail, and beside the fixed Points.java, where every test must pass.
So ask for the balance of a phone that is not in the map (a test with phones that have points passes on the bug too), and check that a phone with points still gets them. No real waiting: each test must finish within 3 seconds.
What you will learn
- Repro.java: a new passenger's balance that crashes
- Points.java: a new passenger's balance is 0
- PointsTest.java: a test that would have caught it
More in Everyday traps
Build "Auto-unboxing null" 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.
The first 2 chapters of Java traps are free. This one comes with the all labs plan.