This code seems to work in Java, violating everything I thought I knew about the language:
int x = 0;
x += 7.4;
x now has the value 7. Of course, one can't just write int x = 7.4, so this behavior seems strange and inconsistent to me.
Why did the developers of Java choose such a behavior?
The question that mine was marked as a duplicate of was actually answering the "what happens" part, but not my main question: what the rationale is.
However, it does use the operator to increment isolated integer variables. It does not use the operator with floats or doubles.
++ (increment)Increases the value of an integer variable by 1. Equivalent to the operation i = i + 1. If the value of the variable i is five, then the expression i++ increases the value of i to 6.
Can I increment by 2 in a for loop in Java? If you want to increment or decrement a variable by an amount other than 1 , you can use += and -= . For example, i += 2 increments i by 2 : int i = 2; while (i <= 8) { System.
Short answer is "no" - the range of values an int can represent and that a double can represent are implementation defined - but a double certainly cannot support every integral value in the range it can represent.
The operators for numbers do all kinds of casting which in this case converts the 7.4 double to a 7 int by rounding it.
What you have here is a Compound Assignment Operators
So what really gets executed is
x= (int)(x + 7.4)
Since x is an int and 7.4 x gets converted to double vs a Binary Numeric Promotion so you get 7.4 as an intermediate result.
The result (a double) is then cast and therefore subject to a Narrowing Primitive Conversion which rounds it to 7
Regarding the new question: Why was it done this way?
Well you can argue long if implicit conversions are a good or bad thing. Java went some kind of middle road with some conversions between primitives, their boxed types and Strings.
The += operator then has a rather simple and straight forward semantics. It really only looks strange if you consider it an increment by operator, instead of what it really is: a shorthand for a combination of operator and assignment.
Sometime back only i read about it It will be actually X= (int)(x + 7.4)
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