Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int can be incremented by a double value

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.

like image 603
Brrch Avatar asked Aug 24 '15 10:08

Brrch


People also ask

Does increment work on double?

However, it does use the operator to increment isolated integer variables. It does not use the operator with floats or doubles.

How do you increment an int?

++ (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 you increment by 2 in Java?

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.

Can a double fit into an int?

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.


2 Answers

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.

like image 97
Jens Schauder Avatar answered Sep 28 '22 10:09

Jens Schauder


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

like image 36
SacJn Avatar answered Sep 28 '22 10:09

SacJn