short s = 10;
s = s + (short)1;
これでコンパイルエラーが起こるのはなぜですか?
この記法はダメなのでしょうか
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。

回答2件
0
ベストアンサー
short + short の返り値は、実はint型なのです。
Java
1class Main { 2 static void func(int arg) { 3 System.out.println("arg type is int"); 4 } 5 static void func(short arg) { 6 System.out.println("arg type is short"); 7 } 8 9 public static void main(String[] args) { 10 short s = 10, t = 11; 11 func(s+t); 12 } 13}
実行結果 Wandbox
arg type is int
ですので、計算結果をshortにキャストしてやらないと代入することができません。
Java
1s = s + (short)1; // NG 2s = (short)(s + (short)1); // OK 3s = (short)(s + 1); // OK 4s += 1; // OK
この辺りの詳しい仕組みはリファレンスの次の部分で説明されています。
####5.6.2. Binary Numeric Promotion
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:
0. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
- Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
・ If either operand is of type double, the other is converted to double.
・ Otherwise, if either operand is of type float, the other is converted to float.
・ Otherwise, if either operand is of type long, the other is converted to long.
・ Otherwise, both operands are converted to type int.
After the conversion(s), if any, value set conversion (§5.1.13) is then applied to each operand.
Binary numeric promotion is performed on the operands of certain operators:
- The multiplicative operators *, /, and % (§15.17)
- The addition and subtraction operators for numeric types + and - (§15.18.2)
- The numerical comparison operators <, <=, >, and >= (§15.20.1)
- The numerical equality operators == and != (§15.21.1)
- The integer bitwise operators &, ^, and | (§15.22.1)
- In certain cases, the conditional operator ? : (§15.25)
引用元:Java Language Specification - Chapter 5. Conversions and Contexts 太字は引用者
投稿2019/04/07 16:27
総合スコア35676
0
エラーの原因は、エラーメッセージに書いてありますので、ちゃんと読むようにしましょう。
「error: incompatible types: possible lossy conversion from int to short」
ちょっと分かりづらいですが、「short 型 + short 型」の計算結果は int 型になります。
なので、以下のように計算結果を short 型にキャストする必要があります。
java
1short s = 10; 2s = (short)(s + 1);
詳細は以下の参考リンクを読んでください。
参考:演算の時の型変換ルール
https://www.javadrive.jp/start/cast/index5.html
投稿2019/04/07 16:21
総合スコア6500
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。