Explain Codes LogoExplain Codes Logo

Convert int to char in java

java
conversion-methods
ascii-equivalent
unicode-code-points
Anton ShumikhinbyAnton Shumikhin·Feb 3, 2025
TLDR

Quick: you need to convert an int to a char in Java. What do you do? Use the (char) cast:

int num = 97; // ASCII for 'a', lower than my current bank balance char ch = (char) num; System.out.println(ch); // Prints 'a'. Bring on the applause!

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

int digit = 5; // Looking digit-ally cool! char charDigit = (char) (digit + '0'); System.out.println(charDigit); // Prints '5', feeling fabulous...

Fancy a different radix?

Use the Character.forDigit method to convert an int to a character in a specified radix (base):

int value = 10; char hexChar = Character.forDigit(value, 16); System.out.println(hexChar); // Prints 'a', hexadecimal rockstar!

Embracing Unicode fully

Higher Unicode code points (> 65535)? Say hello to Character.toChars:

int codePoint = 0x1F600; // I've got a smiley in my pocket. Wanna see? char[] chars = Character.toChars(codePoint); System.out.println(chars); // Prints '😀', spreading joy one character at a time!

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:

int someDigit = 3; // Just a digit, minding its own business... char directChar = (char) (someDigit + 48); // Voila! It's a char now!

The reverse journey

Character.digit method will take your char and bring it back as an int:

char character = '9'; // Just a digit, chilling... int digit = Character.digit(character, 10); System.out.println(digit); // Prints 9, welcome back buddy!

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 char in Java speaks Unicode, not just ASCII.

Keep an eye on your conversions

Transfixed by the magical transformations? Validate with a system output:

System.out.println("(char)49 is: " + (char)49); // Prints '1'. Abracadabra!