Monday, February 21, 2011

CrazyEngineers Forum - Computer Science & IT Engineering

CrazyEngineers Forum - Computer Science & IT Engineering


Java: double to int automatic conversion

Posted: 20 Feb 2011 08:27 AM PST

Code:

int i = 1;
i = i + 1.2;

would result in compile time error. I understand that i + 1.2 would result in a float which can't be assigned to integer.

This code is error free and the result is an integer.
Code:

int i = 1;
i += 1.2;

This automatic narrowing is mind boggling.

Edit:
Had been searching for answer the whole day and someone finally answered it.

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.
from: http://java.sun.com/docs/books/jls/t...ions.html#5281

No comments:

Post a Comment