Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit conversion in java operator +=

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
  • 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.

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

Can someone explain this behavior.

EDIT: I've posted this code block in https://compilr.com/cguedes/java-autoassignment-error/Program.java

like image 700
Carlos Guedes Avatar asked Dec 08 '12 19:12

Carlos Guedes


People also ask

What is implicit conversions in Java?

This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This happens when the two data types are compatible and also when we assign the value of a smaller data type to a larger data type.

Does Java have implicit type conversion?

Implicit Type ConversionJava converts shorter data types to larger data types when they are assigned to the larger variable. For example, if you assign a short value to an int variable then Java does the work for you and converts the short value to an int and stores it in the int variable.

What is implicit conversion example?

Here, we are assigning the double value 34.78 to the integer variable number. In this case, the double value is automatically converted to integer value 34. This type of conversion is known as implicit type conversion. In C, there are two types of type conversion: Implicit Conversion.

What is implicit conversion in programming?

Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.


1 Answers

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

The Java Language Specification says:

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.

So i += f is equivalent to i = (int) (i + f).

like image 141
Louis Wasserman Avatar answered Sep 19 '22 20:09

Louis Wasserman