Java @ mock
short
最終更新:
Bot(ページ名リンク)
-
view
short
Javaにおいてshortはプリミティブ型の1つです。
shortはメモリ領域を16ビット確保します。
shortは符号付き整数を扱うので、2の15乗(32768)より、値の範囲は-32768~32767となります。
shortはメモリ領域を16ビット確保します。
shortは符号付き整数を扱うので、2の15乗(32768)より、値の範囲は-32768~32767となります。
short 使用例 1
ShortSample1.java
class ShortSample1 {
public static void main([[String]] [] args) {
short shortMax = 32767;
short shortMin = -32768;
System.out.println("shortMax:" + shortMax);
System.out.println("shortMin:" + shortMin);
}
}
実行結果
C:\java>javac ShortSample1.java C:\java>java ShortSample1 shortMax:32767 shortMin:-32768
short 値範囲を超えた場合 1
ShortSample2.java
class ShortSample2 {
public static void main(String [] args) {
short shortMax = 32768;
short shortMin = -32769;
System.out.println("shortMax:" + shortMax);
System.out.println("shortMin:" + shortMin);
}
}
コンパイル結果
C:\java>javac ShortSample2.java
ShortSample2.java:4: 精度が落ちている可能性
検出値 : [[int]]
期待値 : short
short shortMax = 32768;
^
ShortSample2.java:5: 精度が落ちている可能性
検出値 : int
期待値 : short
short shortMin = -32769;
^
エラー 2 個
以上のようにコンパイルエラーが起こります。
short 値範囲を超えた場合 2
ShortSample3.java
class ShortSample {
public static void main(String [] args) {
short shortMax = 32767;
short shortMin = -32768;
System.out.println("shortMax - shortMin:" + (shortMax - shortMin));
}
}
実行結果
C:\java>javac ShortSample3.java C:\java>java ShortSample3 shortMax - shortMin:65535
問題なく動きました。数値リテラルがint型なので、自動的に型の拡大変換が行われたのだと思います。
以下のプログラムで明示的にshortを指定して試してみます。
以下のプログラムで明示的にshortを指定して試してみます。
short 値範囲を超えた場合 3
ShortSample4.java
class ShortSample4 {
public static void main(String [] args) {
short shortMax = 32767;
short shortMin = -32768;
System.out.println("shortMax - shortMin:" + (short)(shortMax - shortMin));
}
}
実行結果
C:\java>javac ShortSample4.java C:\java>java ShortSample4 shortMax - shortMin:-1
上記プログラムは本来なら32767-(-32768)で
shortの値範囲を超えてしまいエラーになりそうですが、shortの値は循環するそうです。
循環するので上記計算は
shortの値範囲を超えてしまいエラーになりそうですが、shortの値は循環するそうです。
循環するので上記計算は
32767-(-32768)
↓
32767+32768
↓ 32768はshort型の範囲を超えているので超えた分が循環し-32768になる
32767-32768
↓
-1
となることがわかります