Casting Primitives in Java

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.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.

2 thoughts on “Casting Primitives in Java”