Topics Index

Append values to StringBuffer

If you need explanation Read this topic

If you need Answer Take test on this topic

Append values to StringBuffer
What will be the output of the following program?
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');

A. Pain
B. Gain
C. Main
D. Some other output
E. Output can not determined
F. Compilation Error or Runtime Error
Topic: Java Random Class - java.util.Random Package

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is D
as Random is "Empty",nothing will happen in switch case
in word there will be ain.

Posted by Mânïshå Mùlchåndânï    2014-06-25 09:01:02

C because rnd.nextInt(2) will be zero

Posted by Akash Kolariya    2014-06-25 09:03:46

ans F .....rnd variable cannot invoke nxtInt() function in main class.

Posted by Manasa Jyothi Sree    2014-06-25 09:05:27

Ans is C since the switch case enter the case 2 and creates object by string G and since there is no break stmt after case 2 the controls goes to next case i.e.default case and again creates object by stringbuffer m and comes iut of switch and appendds string a,i,n hence Main is output

Posted by Vicky Maduri    2014-06-25 09:06:01

ans d..ain
r.nxtint(2) generate values 0-1,
but w value s nt changd bcz stringbuffer used to declar final.
so w value cant change.
outsid switch case ,a i n chars are appended with null value.
so output prints ain.switch case pasd but ptints nothing

Posted by Maheshwari Natarajan    2014-06-25 09:32:12

Ans:D (ain)
Explanation:It will be "zero" in switch case.So the output will be ain(D)

Posted by Hari Krishna    2014-06-25 11:03:57

Congratulations Mânïshå Mùlchåndânï. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-06-26 04:35:04

© meritcampus 2019

All Rights Reserved.

Open In App