Convert int to char in java
Quick: you need to convert an int to a char in Java. What do you do? Use the (char) cast:
Here, num is a Unicode code point (0-65535). The char produced mirrors the Unicode character represented by the int.
Deep dive: Unraveling the cast
Let's explore the finer details with other conversion methods:
Working with digits
Working with single digits? Simply add 48 — the ASCII equivalent of '0':
Fancy a different radix?
Use the Character.forDigit method to convert an int to a character in a specified radix (base):
Embracing Unicode fully
Higher Unicode code points (> 65535)? Say hello to Character.toChars:
Some tips
- Casting is clean, but forgets about different radices.
- Adding 48 only works for single-digit numbers.
- Keep the ASCII or Unicode table close for mapping insights.
Extra tricks: Making magic
Digits into characters
A handy way to convert a digit into a char without extra string manipulations:
The reverse journey
Character.digit method will take your char and bring it back as an int:
Pitfalls to avoid
(char)cast can behave like a naughty child with values outside printable character range.- Direct assignment may summon unexpected Unicode monsters.
- A
charin Java speaks Unicode, not just ASCII.
Keep an eye on your conversions
Transfixed by the magical transformations? Validate with a system output:
Was this article helpful?