Int can be doubled

This code seems to work in Java, breaking everything that I thought about knowing the language:

int x = 0;
x += 7.4;

x now has the value 7. Of course, you can't just write int x = 7.4 , so this behavior seems strange and inconsistent to me.

Why did the Java developers choose this behavior?

The question that mine was marked as a duplicate actually answered the question "what is happening", but not my main question: what is the rationale.

+4
source share
4 answers

The operators for numbers perform all kinds of castings, which in this case convert 7.4 double to 7 int by rounding it.

, ,

x= (int)(x + 7.4)

x - int, 7.4 x double vs Binary Numeric Promotion, 7.4 .

(double) , 7

: ?

, , - . Java - , .

+ = . , , , : .

+3

- X = (int) (x + 7.4)

+1

. . .

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

int long float double - . IEEE 754, (§4.2.4).

+1
source

In my opinion x = 7 due to basic conversion

0
source

All Articles