Casting Between char and Integer Types
What you'll learn: How Java's char type automatically converts to integers and how to convert integer values back to characters using explicit casts.
The Dual Nature of char
In Java, char is both a character type and a numeric type. Every character is secretly stored as a 16-bit unsigned integer representing its Unicode code point. For example, the letter 'A' is stored as the number 65.
Automatic Widening: char to int
When you use a char in a numeric context, Java automatically widens it to an int. This is safe because no information is lost—the Unicode value simply gets promoted to a larger integer type.
char letter = 'A';
int code = letter; // Automatic widening: 65
System.out.println(code); // Prints: 65
You can perform arithmetic on char values, and Java will automatically convert them to int:
char c = 'C';
int result = c + 2; // c becomes 67, adds 2 = 69
System.out.println(result); // Prints: 69
Narrowing Back: int to char
Going the other direction requires an explicit cast because you're narrowing from a larger type to char. This tells the compiler you understand the potential risks:
int code = 66;
char letter = (char) code; // Explicit cast required
System.out.println(letter); // Prints: B
If the integer value is outside the valid Unicode range (0 to 65,535), the result will be truncated and may produce unexpected characters.
Key Takeaway: char automatically widens to int based on Unicode code points, but converting an integer back to char requires an explicit cast like (char) value.