2017-03-02 11 views
-1

なぜこのエラーでこの整数大きすぎる - コンパイルエラー

int a = 2147483648; 

結果:

Test.java:3: integer number too large: 2147483648 
int a = 2147483648; 
     ^1 error 

しかし、これはそのコンパイラエラーなしで動作しますか?

int a = Integer.MAX_VALUE + 1; 
+3

ロールオーバーを追加したとき。あなたが定数としてそれをエンコードするなら、それはしません。 –

+1

'int'に収まらない数字と何かの違いは何ですか?まあ...最初は収まりません。理由がわからない場合は、2番目の作品は:https://en.wikipedia.org/wiki/Integer_overflow – Tom

答えて

0

も同様に無効です。

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 )。

2

これは、追加するときに整数が折り返されるためです。

+1

プラスワン - 短い、甘い、ポイントに。 – cbmeeks

2

は、main関数の最後にこれを追加します。

System.out.println(a); 

あなたはInteger.MAX_VALUE + 1;-2147483648に「ロールオーバー」ことがわかります。次のようにそれは、実際にあなたの譲渡の目的地は、タイプintの変数であることは重要ではありませんです

関連する問題