Open In App

A Java Random and StringBuffer Puzzle

Improve
Improve
Like Article
Like
Save
Share
Report

Predict the output of the program




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);
    }
}


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’.


Last Updated : 20 Oct, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads