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
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.
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.
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.
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.
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 toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
So i += f
is equivalent to i = (int) (i + f)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With