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

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

问题描述

我发现 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 value 3, and the variable i maintains the value 3.

      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)),其中 TE1 的类型,除了 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天全站免登陆