The Riddle of Java--a speech from Neal Gafter __java

Source: Internet
Author: User

Translation staff: Anchor

Translation Date: November 20, 2013

Source text link: A puzzle from "a Brief History of the (Java) world and A Peek Forward" presented by Neal Gafter

Here's a Java riddle from Neal Gafter's speech:

Import Java.util.Random;
Rhymes, rhyme public
class Rhymes {
    private static Random rnd = new Random ();
    /**
     * What could be the output of the following program?
     * (a) Pain, Gain or main (according to each random number)
     * (b) Pain or main (according to random number)
     * (c) Main (always this)
     * (d) None of the above is not
    * * * 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);
    }

Which is the correct answer?

The correct answer is D.
There are three flaws in the program:

1. Obviously, there is no break in the switch statement

2. Nextint (2) The result returned is only 0 or 1

3. ' P ', ' G ', ' M ' is a char-type hand, not a string object, so it is automatically converted to an int and a constructor that does not conform to the expected function is invoked.

For more information, refer to the books of Joshua Bloch and Columbia (Neal gafter), "Java FAQ"

Related reading:

Ten common Java string issues
Declaration, initialization and scoping for Java Java Code:given range, return an array of N random numbers constructor C An Throw exceptions in java!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.