将int添加到short [英] Adding int to short

查看:192
本文介绍了将int添加到short的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位同事向我提出这个问题,我有些困惑。

A colleague of mine asked this question to me and I am kind of confused.

int i = 123456;
short x = 12;

声明

x += i;

编译罚款

x = x + i;

什么是Java在这儿干?

What is Java doing here?

推荐答案

int i = 123456;
short x = 12;
x += i;

实际上是

int i = 123456;
short x = 12;
x = (short)(x + i);

x = x + i 简直就是 x = x + i 。它不会自动转换为 short ,从而导致错误( x + i 的类型为 int )。

Whereas x = x + i is simply x = x + i. It does not automatically cast as a short and hence causes the error (x + i is of type int).


复合赋值表达式表格 E1 op = E2 相当于 E1 =(T)((E1)op(E2)),其中 T E1 的类型,但 E1 除外只评估一次。

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

- JLS§15.26.2

这篇关于将int添加到short的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆