在Java之间的short,int,long,double,float之间进行转换 [英] casting between short,int,long,double,float in Java

查看:1111
本文介绍了在Java之间的short,int,long,double,float之间进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

推荐答案

这些都是由JLS中的二进制数字促销规则指定的。从 http:// docs。 oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2

解决方案

当操作员将二进制数字升级应用于一对
操作数时,每个操作数必须表示可转换为
数字类型的值,按以下顺序应用以下规则:

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:


  1. 如果任何操作数是引用类型,它将被取消装箱
    转换(§5.1.8)。

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:

扩展原语转换(§5.1.2)适用于转换任何一个或
两个操作数,按以下规则指定:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).


  • 如果任一操作数的类型为double,则另一个转换为double。

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

否则,如果任一个操作数的类型为float,另一个将
转换为float。

  • If either operand is of type double, the other is converted to double.

否则,如果任一操作数的类型为long,另一个是将
转换为long。

Otherwise, if either operand is of type float, the other is converted to float.

否则,两个操作数都转换为int型。

Otherwise, if either operand is of type long, the other is converted to long.


Otherwise, both operands are converted to type int.

转换类型后,如果有的话,值集合转换(§5.1.13)是
操作数。

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:


  • 乘法运算符*,/和%(§15.17)

  • The multiplicative operators *, / and % (§15.17)

数字类型+和 -
的加法和减法运算符

The addition and subtraction operators for numeric types + and - (§15.18.2)

数值比较运算符< =,>和> =(§15.20.1)

The numerical comparison operators <, <=, >, and >= (§15.20.1)

数字等价运算符==和!=(§15.21.1)

The numerical equality operators == and != (§15.21.1)

整数运算符& ^,和| (§15.22.1)

The integer bitwise operators &, ^, and | (§15.22.1)

在某些情况下,条件运算符? (§15.25)

In certain cases, the conditional operator ? : (§15.25)

(值集转换浮点表示。)

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

这篇关于在Java之间的short,int,long,double,float之间进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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