在Java推广? [英] Promotion in Java?

查看:124
本文介绍了在Java推广?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

促销规则是当操作数属于不同类型时,自动二进制数字提升会发生,较小的操作数类型会转换为较大的操作数。但是操作数是相同类型的,例如,

The rules for promotion is "when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger". But the operands are of same type for example,

byte=byte+byte // Compile time error... found int..

那为什么会这样?

推荐答案

字节没有+运算符。相反,两个操作数都被提升为int,所以你有

There's no + operator for byte. Instead, both operands are promoted to int, so you've got

byte = byte + byte
... becomes (widening to find + operator) ...
byte = int + int
... becomes (result of + operator) ...
byte = int 

...然后失败,因为没有从 int 隐式转换为字节。你需要施放:

... which then fails because there's no implicit conversion from int to byte. You need to cast:

byte a = 1;
byte b = 2;

byte c = (byte) (a + b);

以下是数字促销的实际规则,来自 JLS的第5.6.2节

Here are the actual rules for numeric promotion, from section 5.6.2 of the JLS:

当运算符将二进制数字提升应用于一对操作数时,每个操作数必须表示可转换为数字类型的值,遵循以下规则,按顺序使用扩展转换(第5.1.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, using widening conversion (§5.1.2) to convert operands as necessary:


  • 如果任何操作数是在引用类型中,执行拆箱转换(第5.1.8节)。然后:

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

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

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

  • 否则,两个操作数均为转换为int。

  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
  • 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.

这篇关于在Java推广?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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