Increment Statements Difference
i was wondering whats the difference between the two
Code :
int x = 0;
x += .1;
x = x + .1;
given that x is an integer type
ofcourse will be an error because .1 is a floating point number
but how come with it doesnt give any error?
Re: Increment Statements Difference
From the Java language specifications:
Quote:
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);
Basically, you get a free implicit cast.
Re: Increment Statements Difference
To add to what helloworld said, this is one of those times that looking at the bytecode might help, as the cast is readily seen in all its details (using 'javap -c MyClass'): the integer is cast to a double, added to said double, then cast to back to an int. javap is not an often used tool, but is nice in situations such as this to answer particular questions regarding compiler mysteries such as this.
Re: Increment Statements Difference
hmmm in my program actually, the game program im writing, there is a method that keeps track of the movement of my animations which has a variable x..
Code :
public void theMethod() {
x += .1;
}
where x is a data member which is an integer type, this method is responsible for the speed of the objects movement(Animation)
i notice that.. when i tried to make it 1 (i.e x += 1) the movement of the object is the same (doest change) even if i make it .1(i.e x += .1) so basically , either .1 or 1 in that statement the movement of the object is the same, i even make a print statement that monitors the movement of that certain object , no matter how i tried to make it .1 or 1, the value is still updating by 1
does it mean that the .1 is being casted or converted to int? converted to 1?
Re: Increment Statements Difference
That's equivalent to (very explicitly spelled out):
Code Java:
x = (int)(((double)x) + 1.0);
Likely, the number you're adding results in something slightly smaller than the next integer. So when it's casted back to an int, it gets truncated. See: What every Computer Scientist should know about floating point arithmetic