java运算符+ =中的隐式转换 [英] implicit conversion in java operator +=

查看:306
本文介绍了java运算符+ =中的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现java编译对于使用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




  • $ c> i + = f 编译不会发出错误,但是exaluation的结果是一个值为 3 变量 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 value 3, and the variable i maintains the value 3.

      i = i + f 表达式中,编译器发出错误:error:possible loss of precision / li>

      In the i = i + f expression the compiler issues an error with "error: possible loss of precision" message.

      有人可以解释此行为。

      代码块,位于 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)) code> T E1 的类型,除了 E1 只有一次。

      A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

      因此 i + = f 等效于 i =(int)(i + f)

      这篇关于java运算符+ =中的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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