6

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.

Brrch
  • 331
  • 1
  • 4

4 Answers4

4

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
1

Sometime back only i read about it It will be actually X= (int)(x + 7.4)

SacJn
  • 777
  • 1
  • 6
  • 16
1

No. it's not inconsistent. It round-to-nearest mode.

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

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

In my opinion x = 7 due to basic conversion