Ben Ben - 4 months ago 10
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
long
if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type
int
(ยง4.2.1)." Section 4.2.2 refers to "The numerical operators, which result in a value of type
int
or
long
." So the result of the addition should, in my understanding, be an
int
, which cannot be assigned to the
char
variable
c
.

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

'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.

Comments