在java中添加两个短变量和两个整数变量之间的区别? [英] Difference between adding two short variables and two integer variables in java?

查看:80
本文介绍了在java中添加两个短变量和两个整数变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是



短a = 10;

短b = 10;

短c = a + b;

在这种情况下,我收到编译错误但在下面的代码中



Int a = 10;

Int b = 10;

Int c = a + b;

我没有得到任何错误,任何人都可以详细解释我已经混淆了这么长时间/>


我尝试了什么:



我已经读过谷歌,好像我们一样添加两个你将获得int类型的短变量

但为什么不可能添加两个转换为double或long变量类型​​的int变量

解决方案

< blockquote>它在Java语言规范中看起来很奇怪:



如果除了移位运算符之外的整数运算符至少有一个long类型的操作数,那么操作使用64位精度执行,数值运算符的结果类型为long。如果另一个操作数不长,则首先将其扩展(第5.1.5节)至typ长期通过数字推广(§5.6)。



否则,操作使用32位精度执行,数值运算符的结果类型为int 。如果任一操作数不是int,则首先将其扩展为通过数字提升键入int。



我的意思是:



短+字节= int

短+短= int

int + short = int

int + int = int

int + long = long

long + long = long



我发现有点不一致,老实说,但这是它的定义方式。


I mean

Short a=10;
Short b=10;
Short c=a+b;
In this case I got compilation error but in below code

Int a=10;
Int b=10;
Int c=a+b;
I didn't get any error any one can explain in detail I have confused so long

What I have tried:

I have Read in Google as if we add two short variables you will get int type
But why it is not possible in adding two int variables converted into double or long variable types

解决方案

It looks to be an oddity in the Java Language Specification:

"If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion."

Which I take to mean:

short + byte = int
short + short = int
int + short = int
int + int = int
int + long = long
long + long = long

I find that a bit inconsistent, to be honest, but that is the way that it's defined.


这篇关于在java中添加两个短变量和两个整数变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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