Java之谜 —— 来自Neal Gafter的演讲

翻译人员: 铁锚

翻译日期: 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解惑

相关阅读:

  1. 十大常见Java String问题
  2. Declaration, Initialization and Scoping for Java
  3. Java Code: Given range, return an array of N random numbers
  4. Constructor Can Throw Exceptions in Java!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值