java int long double,在Java之间的short,int,long,double,float之间进行转换

As i understand, when you cast between 2 of these types with an arithmetic operation in Java, for example double + int, the result will be as the bigger type (meaning in this example, the result will be double). What happens when you make an arithmetic operation on 2 types with the same size? what will int + float and long + double give? since int and float are 4 bytes each, and long and double are 8 bytes.

解决方案

This is all specified by the binary numeric promotion rules in the JLS. From http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2:

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:

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 type conversion, if any, value set conversion (§5.1.13) is

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)

("value set conversion" is about mapping between floating-point representations.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值