This week I attended the very first and very well organized conference What’s Next ? in Paris and one of the speakers was Neil Gafter, co-author of the book “Java™ Puzzlers: Traps, Pitfalls, and Corner Cases” (2005).
He shared with us 2 or 3 puzzlers which I will share here too :
Question 1) What will the following program print ?
import java.util.Random; public class Rhymes { private static Random rnd = new Random(); public static void main(String[] args) { StringBuffer word = null; switch(rnd.nextInt(2)) { case 1: word = new StringBuffer('P'); case 2: word = new StringBuffer('G'); default: word = new StringBuffer('M'); } word.append('a'); word.append('i'); word.append('n'); System.out.println(word); } }
1) Pain
2) Gain
3) Main
4) ain
Answer :
It does not print Pain, Gain or Main ! It always prints ain ! There are 3 bugs in this program.
A few explanations :
a) The only possible values of the expression rnd.nextInt(2) are 0 and 1
b) remember “break” in “switch” element !
c) new StringBuffer(‘M’) ==> it’s actually the new StringBuffer(int) constructor which is used !
A corrected version is :
import java.util.Random; public class Rhymes { private static Random rnd = new Random(); public static void main(String[] args) { StringBuffer word = null; switch(rnd.nextInt(3)) { case 1: word = new StringBuffer("P"); break; case 2: word = new StringBuffer("G"); break; default: word = new StringBuffer("M"); break; } word.append('a'); word.append('i'); word.append('n'); System.out.println(word); } }
Question 2) What does the following program print ?
public class Elementary { public static void main(String[] args) { System.out.println(12345 + 5432l); } }
1) 66666
2) 17777
Answer : 17777
Explanation :
5432l
is actually a long, not an int.
l
is the lowercase letter el, it is not the digit 1.
So a good practice is to use capital el (L) in long literals, not a lowercase el (l) :
System.out.println(12345 + 5432L);
You must be logged in to post a comment.