Simple question about Java

O

overbored

When I do "b = b + 1" for a byte b, what's really going on? Is b being
promoted to an int, and the result is an int? Why isn't the compiler able
to deal with this, but is able to accept "b += 1"? Thanks in advance.
 
T

Tor Iver Wilhelmsen

overbored said:
When I do "b = b + 1" for a byte b, what's really going on? Is b
being promoted to an int, and the result is an int? Why isn't the
compiler able to deal with this, but is able to accept "b += 1"?
Thanks in advance.

"b += 1" is a special case, which has a "built-in" cast to byte. See
the language specification for details.
 
O

Oscar kind

overbored said:
When I do "b = b + 1" for a byte b, what's really going on? Is b being
promoted to an int, and the result is an int? Why isn't the compiler able
to deal with this, but is able to accept "b += 1"? Thanks in advance.

As Tor already answered, "b += 1" is a special case.

As for "b = b + 1", I believe this happens:
- The value of b (not b itself) is promoted to an int;
- An addition with the constant 1 is done;
- The result won't fit into a byte, thus a compiler error occurs.
The compiler cannot handle it automatically, as it is not a widening
conversion; the compiler is not allowed to handle this on itself.

If the result is cast to a byte, the result is assigned to b.
 
M

Michael Borgwardt

overbored said:
When I do "b = b + 1" for a byte b, what's really going on? Is b being
promoted to an int, and the result is an int?
Exactly.

Why isn't the compiler able
to deal with this,

Why should it be able to? What if b is 128 (the largest value a byte can hold)
prior to the statement?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,233
Latest member
AlyssaCrai

Latest Threads

Top