• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Quiz?  RSS feed

 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When is this statement legal:
x = x + i;
but this is not:
x += i;
 
Nicole Lacoste
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your question was:

When is this statement legal:
x = x + i;
but this is not:
x += i;

But I think you mean it the other way around?

x += i is legal and
x = x + i is not.

Java automatically casts stuff to int to do adds, but += automatically casts a second time to the type of x in our case. If x is of type short or byte, x + i is of type int, you can't set an short with an int.

Niki
 
Grey Lisztjowicz
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
CS -- I think the issue here is that most modern computers do all integral arithmetic at 32-bit or 64-bit precision. If i and x are integers (which includes int, char, byte, short), the CPU is going to do the math using 32 bits or 64 bits, and may not be able to fit the result back into a char/byte/short. Also, any sign value (+/-) may be lost.

There are two ways (I can think of) to get around this; use casts, or just don't use char/byte/short unless you really need them.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Grey Lisztjowicz:
most modern computers


Note that one of the lovely things about Java is that the hardware doesn't matter; the size and layout of all data types is fixed by the language specification. For Java, such questions can be answered precisely and the answers hold for all platforms.

As for the OP's question, I can also think of examples that go the other way (where the += version is the legal one) but no examples as posted, so if that's not a mistake, it's a good brain teaser!

So what's the answer?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!