Casting Primitives in Java
Apr 9, 2010
The subtleties of the Java programming language can have some interesting implications. Sometimes a subtlety can create real problems. Here’s a question that underscores that point:
What is the result of compiling and executing the following Java code?
char x1 = 'A';
char x2 = x1 + 1;
a) x2 = 'B'
b) x2 = 65
c) You cannot do math with a char data type
d) The code will not compile
The answer is d). Do you see the problem?
The expression x1 = x2 + 1 is the culprit, of course, but why? It’s the literal 1. By default, Java will consider that literal as an int data type and not a char.
Mathematical operations in Java will implicitly cast the result of an operation to the widest scope member. As a result, the operation produces an int. A char is a two byte value and an int is a four byte value. While primitive Java data types can be implicitly cast to a wider scope, it requires an explicit cast to narrower scopes. The possibility that the expression could return a value too large for a char to hold (possibly truncating the result) is something the Java compiler won’t allow unless it is explicitly given permission.
If the expression were rewritten as follows
char x2 = (char)(x1 + 1);
the compiler would understand your intentions and compile it without complaint.
Check out Introduction to Java Training for New Programmers, which we run monthly. It’s a great opportunity to get started with Java.