短加短是一个整数 [英] short plus short is an int

查看:59
本文介绍了短加短是一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个简短的变量. 当我将两个加在一起并将结果分配给第三个时,eclipse告诉我需要将其强制转换为short!

I have three short variables. When I add two together and assign the result to the third, eclipse tells me that I need to cast it to a short !

short sFirst, sSecond, sThird;

sFirst = 10;
sSecond = 20;
sThird = sFirst + sSecond;

但是,当我执行简单的任务,然后进行增量任务时,一切都很好.

Hovever, when I do a simple assignment followed by an incremental assignment, all is fine.

short sFirst, sSecond, sThird;

sFirst = 10;
sSecond = 20;
sThird = sFirst;
sThird += sSecond;

这是为什么?

推荐答案

JLS(

"二进制+运算符在应用于两个数字类型的操作数时会执行加法运算,从而产生操作数之和."

"在操作数上执行二进制数值提升(

"Binary numeric promotion is performed on the operands (§5.6.2)."

这意味着表达式的操作数将转换为int.因此,加法会将int添加到int.

That means that the operands of your expression are converted to int. So the addition will add an int to an int.

"数字操作数上加法表达式的类型是其操作数的提升类型."

您的情况是int.

我不会猜测为什么这样做.但是,这绝非偶然.如果查看JVM规范中定义的字节码指令集,将会看到intlongfloatdouble的算术指令,但是较小的整数类型则没有.

I won't speculate as to why it is done this way. However, it is no accident. If you look at the bytecode instruction set as defined in the JVM spec, you will see that there are arithmetic instructions for int, long, float and double ... but NOT for the smaller integer types.

这篇关于短加短是一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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