3. Puzzlers with Character
This chapter contains puzzles that concern strings, characters, and other textual data.
Puzzle 11: The Last Laugh
What does the following program print?
public class LastLaugh { public static void main(String args[ ] ) { System.out.print("H" + "a"); System.out.print('H' + 'a'); }}
Solution 11: The Last Laugh
If you are like most people, you thought that the program would print HaHa
. It looks as though it concatenates H
to a
in two ways, but looks can be deceiving. If you ran the program, you found that it prints Ha169
. Now why would it do a thing like that?
As expected, the first call to System.out.print
prints Ha
: Its argument is the expression "H"
+ "a"
, which performs the obvious string ...
Get Java™ Puzzlers: Traps, Pitfalls, and Corner Cases now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.