A Java Random and StringBuffer Puzzle

Predict the output of the program

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.util.Random;
public class GFG {
    private static Random rd = new Random(); 
    public static void main(String[] args) {
    StringBuffer word = null;
    switch(rd.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);
    }
}

chevron_right


Solution:
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 contribute@geeksforgeeks.org. 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.



My Personal Notes arrow_drop_up