Ben Ben - 1 year ago 88
Java Question

Integer arithmetic in Java with char and integer literal

Can someone explain to me why the following code compiles OK in Java?

char c = 'a' + 10;

Why is this not equivalent to the following, which does not compile?

int i = 10;
char c = 'a' + i;

The Java Language Specification (section 3.10.1) states "An integer literal is of type
if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type
(ยง4.2.1)." Section 4.2.2 refers to "The numerical operators, which result in a value of type
." So the result of the addition should, in my understanding, be an
, which cannot be assigned to the

However, it compiles fine (at least in Sun JDK 1.6.0 release 17 and in Eclipse Helios).

Rather an artificial example perhaps, but it is used in an introductory Java course I have been teaching, and it now occurs to me that I don't really understand why it works.

Answer Source

'a' + 10 is a compile-time constant expression with the value of 'k', which can initialise a variable of type char. This is the same as being able to assign a byte variable with a literal integer in [-128, 127]. A byte in the range of [128, 255] may be more annoying.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download