Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+= int and double conversion [duplicate]

Tags:

java

Possible Duplicate:
Varying behavior for possible loss of precision

int testing = 0;
testing += 2.0

the above code compiles.

where as

int testing = 0;
testing = testing + 2.0;

this code doesn't compile. Any idea why?

like image 645
Subu Avatar asked May 25 '10 14:05

Subu


People also ask

Can an int be converted to a double?

We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. It is also known as implicit type casting or type promotion.

What happens if you convert double to int?

As we all know, a Double primitive contains decimal digits. On conversion of these values to integers, the decimal digits get truncated, by rounding off the number to the nearest integer according to the method you choose. Java provides the following three ways to convert Double values to integer numbers: TypeCasting.

Can we convert int to double in C++?

The values of int data type and double data type will be printed through the C++ cout command. Before assigning the int value to the double variable, the compiler transforms it to double automatically.


1 Answers

Compound assignment has a hidden cast in Java.

JLS 15.26.2 Compound Assignment Operators:

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.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

Related questions

  • Varying behavior for possible loss of precision
like image 192
polygenelubricants Avatar answered Oct 11 '22 06:10

polygenelubricants