0

データ型が上位のデータ型 byte-short-int に自動的に昇格されることを知っています

class Temp {
    void check(byte x) {
        System.out.println(x + " is the byte type");
    }

    void check(short x) {
        System.out.println(x + " is the short type");
    }

    void check(int x) {
        System.out.println(x + " is the int type");
        int y = x;
        System.out.println(y + " is the int type");
    }

    void check(long x) {
        System.out.println(x + " is the long type");
    }

    void check(float x) {
        System.out.println(x + " is the float type");
    }

    void check(double x) {
        System.out.println(x + " is the double type");
    }

    public static void main(String args[]) {
        byte b = 42;
        char c = 'a';
        short s = 1024;
        int i = 50000;
        float f = 5.67f;
        double d = .1234;
        double result = (f * b) + (i / c) - (d * s);
        System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
        System.out.println("result =" + result);
        Temp t = new Temp();
        t.check(f * b);
        t.check(i / c);
        t.check(d * s);
        t.check(b + b);
        t.check(b * b);
        t.check(b * b * b);
        t.check(b * b * b * b * b * b * b * b * b);
        t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
                * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b);
        t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
                * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
                * b * b * b * b * b);

    }
}

出力:

238.14 + 515 - 126.3616
result =626.7784146484375
238.14 is the float type
515 is the int type
515 is the int type
126.3616 is the double type
84 is the int type
84 is the int type
1764 is the int type
1764 is the int type
74088 is the int type
74088 is the int type
-1889539584 is the int type
-1889539584 is the int type
-2147483648 is the int type
-2147483648 is the int type
0 is the int type
0 is the int type

私の質問は、42 + 42 = 84でバイト範囲が-128から127であるため、b * bがintに昇格する理由です。84は範囲内です。さらに、なぜか

t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
                * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b);

この行は 0 になりました。これを倍増させてみませんか。

4

1 に答える 1

5

私の質問は、なぜ b*b が int に昇格するのかということです

それは、言語仕様がそうするだろうと言っているからです。

そして、なぜ[...]この行が0になったのに、なぜその倍に昇格しないのですか

繰り返しますが、それは言語の定義方法ではないためです。

JLS のセクション 15.17 を読んでください。

乗法演算子は同じ優先順位を持ち、構文的に左結合です (左から右にグループ化されます)。

乗算演算子の各オペランドの型は、プリミティブ数値型に変換可能な型 (§5.1.8) である必要があります。そうしないと、コンパイル時エラーが発生します。

バイナリ数値昇格は、オペランドで実行されます (§5.6.2)。

バイナリ数値昇格 ( 5.6.2 ) はbyteオペランドをintに昇格させるためint * int、コード内のすべてのケースで算術演算が行われます。最初のケースでは、両方のオペランドが;byte * byteに昇格されます。int長い行の場合、1 つがbyte * byteあり、残りはint * byteで、2 番目のオペランドだけが に昇格されintます。この選択はコンパイル時に行われ、実行時の値とは関係ありません。JVM は、値doubleが の境界をオーバーフローするため、値を にプロモートすることを決定しませんint

于 2013-10-16T19:58:24.810 に答える