Java之謎 —— 來自Neal Gafter的演講__Java

來源:互聯網
上載者:User

翻譯人員: 鐵錨

翻譯日期: 2013年11月20日

原文連結: A Puzzle from “A Brief History of the (Java) World and a Peek Forward” Presented by Neal Gafter

以下是來自Neal Gafter 演講中的一個Java謎題:

import java.util.Random;// Rhymes,押韻public class Rhymes {    private static Random rnd = new Random();    /**     * 以下程式的輸出有可能是什麼?     * (a) Pain ,Gain 或者 Main (根據各個隨機數)     * (b) Pain 或者 Main (根據隨機數)     * (c) Main (總是這個)     * (d) 以上都不對     */    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);    }}
正確答案是哪一個呢?

正確答案是 D.
該程式中有三處缺陷:

1.  顯然,在 switch語句中沒有 break

2. nextInt(2) 返回的結果只有 0  或者 1

3. ‘P’, ‘G’, ‘M’ 是char型手, 而不是String對象,所以被自動轉換為int型,調用了不符合預期的建構函式.

如果想要瞭解更多,請參考布洛克(Joshua Bloch)與 加夫特(Neal Gafter)的圖書, 《Java解惑》

相關閱讀:

十大常見Java String問題
Declaration, Initialization and Scoping for Java Java Code: Given range, return an array of N random numbers Constructor Can Throw Exceptions in Java!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.