byte/short加算はint

774 ワード

例を挙げる
public class Test {

    public static void main(String[] args) {
        short a, b, c;   // line 1
        a = 1;  // line 2
        b = 2;  // line 3
        a += 2; // line 4
        a = a + 2;  // line 5
        c = a + b;  // line 6
    }
}

上の例では、ライン5とライン6でコンパイルが通らない場合がありますが、最初は退屈でしたが、ライン4とライン5は等価ではないでしょうか.そしてライン6の2つが同じタイプに加算されて、得られるタイプはまだ同じではありませんか??後で資料を調べて
the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

住所は以下の通りです.https://stackoverflow.com/questions/477750/primitive-type-short-casting-in-java
もともと右側に算術式があればintを返すのがデフォルトで、またintより精度が高い場合は精度を下げることはないのでshortとbyteタイプのみに影響します.一方、a+=2の右側には数式がないので、コンパイルは通過できます.a+2またはa+bのデフォルトはintタイプを返します.