Command Palette

Search for a command to run...

Back to the lesson: Topic 16.3 — Tricky Output Questions
Core Java · Example 1 of 6 Java 9+

Puzzles 1: boxing, caching and collections

7) removes "b" without an exception: after the removal the size is 2 and the iterator's cursor is 2, so hasNext() returns false and the modification check in next() never runs. 8) Arrays.asList(int[]) is a List<int[]> holding one array, because generics can't hold primitives.

Small programs whose output surprises most people: Integer caching, the String pool, char arithmetic, overload resolution, initialisation order, finally overriding return, i++ + ++i, floating point and NaN. Predict each answer, then run it; every output here was produced by a real JDK.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that shows Integer == failing for a value outside the cache and fix it with equals. Print both results.

02

Write a method average(int[] values) that returns a double, and show the integer-division bug and its fix for the input {1, 2}.

03

Write a puzzle of your own about finally, predict its output, then write the program and confirm it.

Explain it without notes

01

What does System.out.println("" + 'a' + 'b' + ('a' + 'b')) print, and why?

02

Why does Integer a = 1000, b = 1000; a == b print false, while int c = 1000; a == c prints true?

03

What is printed by double d = 10 / 4; System.out.println(d); and how do you get 2.5?

04

What does Math.min(-0.0, 0.0) return, and why does it differ from comparing with <?

05

A parent constructor calls an overridden method that prints a final field of the child initialised in its declaration to 42. What is printed?

Puzzles 1: boxing, caching and collections Java 9+
Sign in to run this example in your browser.

Expected output

1) true
2) false true
3) false true
4) 1.0
5) [30]
6) 5
7) [a, c]
8) 1
9) NullPointerException