A Java Random and StringBuffer Puzzle
Predict the output of the program
At first glance, this program might appear to print out the words Pain, Gain, and Main with equal likelihood, varying from run to run. But the output of the program is always ain.
Three bugs conspire to cause this behaviour. Lets see them individually:-
1. rd.nextInt(2) will return number between 0(inclusive) and 2(exclusive) which are 0 and 1. Therefore, our program never prints ‘Pain’.
2. The second bug is that there are no break statements between the cases. Whatever the value of the switch expression, the program will execute that case and all subsequent cases. Each case assigns a value to the variable word, and the last assignment wins. The last assignment will always be the one in the final case (default), which is new StringBuffer(’M’). This suggests that the program will never print ‘Gain’ either.
3. The last and most subtle bug is that the expression new StringBuffer(’M’) probably does not do what you think it does. There is no StringBuffer(char) constructor. But there is one that takes an int indicating its initial capacity. In this case, the compiler selects the int constructor, applying a widening primitive conversion to convert the char value ’M’ into the int value 77. In
other words, new StringBuffer(’M’) returns an empty string buffer with an initial capacity of 77. The remainder of the program appends the characters a, i, and n to the empty string buffer and prints out its contents, which are always ‘ain’.
This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.