O'Reilly logo

Java™ Puzzlers: Traps, Pitfalls, and Corner Cases by Neal Gafter, Joshua Bloch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required