Puzzles 3: arithmetic and floating point
13) (float) 0.1 prints as 0.1, but when compared with the double 0.1 it is widened to 0.10000000149011612, a different number.
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.
Write a program that shows Integer == failing for a value outside the cache and fix it with equals. Print both results.
Write a method average(int[] values) that returns a double, and show the integer-division bug and its fix for the input {1, 2}.
Write a puzzle of your own about finally, predict its output, then write the program and confirm it.
Explain it without notes
What does System.out.println("" + 'a' + 'b' + ('a' + 'b')) print, and why?
Why does Integer a = 1000, b = 1000; a == b print false, while int c = 1000; a == c prints true?
What is printed by double d = 10 / 4; System.out.println(d); and how do you get 2.5?
What does Math.min(-0.0, 0.0) return, and why does it differ from comparing with <?
A parent constructor calls an overridden method that prints a final field of the child initialised in its declaration to 42. What is printed?
Expected output
1) 12 i=7
2) 5
3) 3 -3 -1 2
4) 0.30000000000000004 false
5) Infinity -Infinity NaN
6) false true true
7) true false
8) -2147483648 -2147483648
9) -56 3 -3 0
10) 3 -2 -3
11) 500654080 86400000000
12) / by zero
13) 0.1 false