Java Reference
In-Depth Information
< Day Day Up >
Puzzle 4: It's Elementary
OK, so the last puzzle was a bit tricky, but it was about division. Everyone knows that division is
tough. This program involves only addition. What does it print?
public class Elementary {
public static void main(String[] args) {
System.out.println(12345 + 5432l);
}
}
Solution 4: It's Elementary
On the face of it, this looks like an easy puzzle— so easy that you can solve it without pencil or
paper. The digits of the left operand of the plus operator ascend from 1 to 5, and the digits of the
right operand descend. Therefore, the sums of corresponding digits remain constant, and the
program must surely print 66666 . There is only one problem with this analysis: When you run the
program, it prints 17777 . Could it be that Java has an aversion to printing such a beastly number?
Somehow this doesn't seem like a plausible explanation.
Things are seldom what they seem. Take this program, for instance. It doesn't say what you think it
does. Take a careful look at the two operands of the + operator. We are adding the int value 1 2345
to the long value 5432 l . Note the subtle difference in shape between the digit 1 at the beginning of
the left operand and the lowercase letter el at the end of the right operand. The digit 1 has an acute
angle between the horizontal stroke, or arm , and the vertical stroke, or stem . The lowercase letter
el , by contrast, has a right angle between the arm and the stem.
Before you cry "foul," note that this issue has caused real confusion. Also note that the puzzle's title
contained a hint: It's El-ementary; get it? Finally, note that there is a real lesson here. Always use a
capital el ( L ) in long literals, never a lowercase el ( l ) . This completely eliminates the source of
confusion on which the puzzle relies:
System.out.println(12345 + 5432 L );
Similarly, avoid using a lone el ( l ) as a variable name. It is difficult to tell by looking at this code
snippet whether it prints the list l or the number 1 :
 
 
Search WWH ::




Custom Search