In Java, given:
int x = 4;
double y = 4.5123;
Why is it permissable to code:
x += y; // in my head I think, "The new value of x is the old value plus y."
But I can't simply assign like this:
x = y;
TIA for answers.
In Java, given:
int x = 4;
double y = 4.5123;
Why is it permissable to code:
x += y; // in my head I think, "The new value of x is the old value plus y."
But I can't simply assign like this:
x = y;
TIA for answers.
Because the language specification says so. A frustrating answer, perhaps – but that's the only correct answer available. Yes, this is a bit odd; the 'assignment operators (+=, -=, *=
, etcetera)' include a free, invisible cast operation. Writing x += y
where x is of type int
and y is some expression of any type is equivalent to x += (int) y
. I'm not quite sure WHY the spec was written the way it is; what I do know: This will never* change; java is not in the habit of making changes which break code written for older versions of java unless there is an extremely good reason, and fixing this weirdness would not be anywhere close to good enough to warrant the change.
NB: Yes, x += y
means 'the new value of x is the old value of x, plus the value of y'.
*) Never say never, yadayada. Let's just say if you gave me 1 in 10,000 odds that this will be different in java within 5 years I'd take the bet, betting that this will not change.