1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Math.abs の戻り値が負の値になる

1
Posted at

問題

次のコードの出力はどうなるでしょうか?

int x = -2147483648;
long y = Math.abs(x);
System.out.println(y);

答え

-2147483648

解説

  • Integer.MIN_VALUE-2147483648(= -2³¹)。
  • int の範囲は -2147483648 ~ 2147483647
  • Math.abs(int) の戻り値は int 型。
  • Math.abs(-2147483648) は理論上 2147483648 になるはずですが、この値は int の範囲を超えてしまいます。

その結果、オーバーフローが発生し、戻り値は変換できずにそのまま -2147483648 になります。

解決策

正しく long 型の正の値にしたい場合は、先に long にキャストしてから Math.abs(long) を利用する必要があります。

int x = -2147483648;
long y = Math.abs((long) x);  // OK
System.out.println(y);        // 2147483648 と出力

環境

  • openjdk 25 2025-09-16
  • javac 25
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?