3

I'm not sure the question is clearly worded, but an example will be clearer.

I found out that will not work in Java:

int a = ...;
a = 5.0;

but this will:

int a = ...;
a += 5.0;

I.e., it seems that the = operator is type safe but += isn't. Is there any deep reason for this or is it just another arbitrary decision language designers must take.

2 Answers 2

5

The reason is that math operations do some implicit casting:

a += 5.0; is evaluated as follows:

a = (int) ((double) a + 5.0);

Assignment, however, requires an explicit cast.

(It might be float rather than double, I don't remember which Java treats as decimal literals.)

3
  • but why is it doing the final cast back to int? Feb 26, 2009 at 15:07
  • (double, f prefix for floats. I believe JavaFX 1.0 uses double and 1.1 uses float.) Feb 26, 2009 at 15:14
  • mipadi, i mean why is it behaving so friendly? "a = a + 5.0" fails too. it could say "a += 5.0" fails aswell. Tom Hawtins answer provides some reason but it's still difficult for me to imagine why java does not just forbid it and introduces just another conversion context (right word?) Feb 26, 2009 at 15:41
1

To make life easier.

Let's go a little further. Consider:

byte b;
...
++b;

The increment is really doing:

b = (byte)(1 + (int)b);

Even using += it doesn't get any better:

b += b;

is:

b = (byte)((int)b+(int)b);

That would make these operators useless for byte/short/char.

Of course I wont be happy until we have arbitrary sized integers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.