Java Reference
In-Depth Information
< Day Day Up >
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 concatenation. The second call to System.out.print is another
story. Its argument is the expression 'H' + 'a' . The problem is that 'H' and 'a' are char literals.
Because neither operand is of type String , the + operator performs addition rather than string
concatenation.
The compiler evaluates the constant expression 'H' + 'a' by promoting each of the char -valued
operands ( 'H' and 'a' ) to int values through a process known as widening primitive conversion
[JLS 5.1.2, 5.6.2]. Widening primitive conversion of a char to an int zero extends the 16-bit char
value to fill the 32-bit int . In the case of 'H' , the char value is 72 and in the case of 'a' , it is 97, so
the expression 'H' + 'a' is equivalent to the int constant 72 + 97 , or 169 .
From a linguistic standpoint, the resemblance between char values and strings is illusory. As far as
the language is concerned, a char is an unsigned 16-bit primitive integer— nothing more. Not so for
the libraries. They contain many methods that take char arguments and treat them as Unicode
characters.
So how do you concatenate characters? You could use the libraries. For example, you could use a
string buffer:
 
 
Search WWH ::




Custom Search