Puzzles 2: strings and chars
7) constPart is a final variable initialised with a constant, so constPart + "va" is a constant expression folded to the pooled "java". part is not final, so part + "va" builds a new String at run time.
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
2) 3=sum
3) 195
4) ab
5) b c 99
6) hello null!
7) true false true
8) false true
9) x 120