java运算符+=中的隐式转换 [英] implicit conversion in java operator +=
问题描述
我发现 java compile 在使用 int 和 float 的赋值和自赋值语句方面具有非预期的行为.
I've found that java compile has a non-expected behavior regarding assignment and self assignment statements using an int and a float.
以下代码块说明了错误.
The following code block illustrates the error.
int i = 3;
float f = 0.1f;
i += f; // no compile error, but i = 3
i = i + f; // COMPILE ERROR
在自赋值
i += f
中,编译不会出错,但计算的结果是一个值为3
的 int,并且变量i
维护值3
.In the self assignment
i += f
the compile does not issue an error, but the result of the exaluation is an int with value3
, and the variablei
maintains the value3
.在
i = i + f
表达式中,编译器发出一个带有error: possible loss of precision" 消息的错误.In the
i = i + f
expression the compiler issues an error with "error: possible loss of precision" message.谁能解释一下这种行为.
Can someone explain this behavior.
我在 https://compilr.com/cguedes/java 中发布了此代码块-autoassignment-error/Program.java
推荐答案
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2
Java 语言规范说:
The Java Language Specification says:
E1 op= E2
形式的复合赋值表达式等价于E1 = (T) ((E1) op (E2))
,其中T
是E1
的类型,除了E1
只计算一次.A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.所以
i += f
等价于i = (int) (i + f)
.这篇关于java运算符+=中的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!