なぜこのエラーでこの整数大きすぎる - コンパイルエラー
int a = 2147483648;
結果:
Test.java:3: integer number too large: 2147483648 int a = 2147483648; ^1 error
しかし、これはそのコンパイラエラーなしで動作しますか?
int a = Integer.MAX_VALUE + 1;
なぜこのエラーでこの整数大きすぎる - コンパイルエラー
int a = 2147483648;
結果:
Test.java:3: integer number too large: 2147483648 int a = 2147483648; ^1 error
しかし、これはそのコンパイラエラーなしで動作しますか?
int a = Integer.MAX_VALUE + 1;
も同様に無効です。
long x = 2147483648; // <-- literal yields "integer too large" error
System.out.println(2147483648); // <-- same issue
問題は、それ自身リテラルであるL
サフィックスなしています、タイプはint
です。最初のエラーのx
のタイプは関連していません。 JLS 3.10.1に関するリテラル1として
:
It is a compile-time error if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator; or if a decimal literal of type int is larger than 2147483648.
この数は、リテラル自体が仕様通りタイプint
のものであっても、int
に割り当てなくてもよいです。ただし、Integer.MAX_VALUE + 1
の場合、このルールは違反されません。以下が有効であること、によって、
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
注:がある
int x = (int)2147483648L;
2147483648L
としてInteger.MAX_VALUE
あり、かつその合計が15.18.2ごとに回り込むよう1
は、有効int
です有効なlong
リテラルであり、キャストはint
に収まるようにこれを切り捨てます。この場合、上記のMAX_VALUE + 1
結果と同じ最終値を返します(特に-2147483648
)。
は、main関数の最後にこれを追加します。
System.out.println(a);
あなたはInteger.MAX_VALUE + 1;
が-2147483648
に「ロールオーバー」ことがわかります。次のようにそれは、実際にあなたの譲渡の目的地は、タイプint
の変数であることは重要ではありませんです
ロールオーバーを追加したとき。あなたが定数としてそれをエンコードするなら、それはしません。 –
'int'に収まらない数字と何かの違いは何ですか?まあ...最初は収まりません。理由がわからない場合は、2番目の作品は:https://en.wikipedia.org/wiki/Integer_overflow – Tom