Character Digit Radix Round Trip

Character.digit maps a char to its value under a radix and forDigit goes back; invalid digits return -1 instead of throwing.

JavaData Integrity

Code

snippet
public class DigitConversions {

    public static void main(String[] args) {
        // hex parsing: 'f' is 15 under radix 16
        System.out.println("hex f=" + Character.digit('f', 16));
        System.out.println("hex 9=" + Character.digit('9', 16));

        // under radix 10 'f' is not a digit: -1 returns instead of an exception
        System.out.println("dec f=" + Character.digit('f', 10));

        // the reverse direction: forDigit maps 15 back to its radix-16 char
        System.out.println("digit 15->" + Character.forDigit(15, 16));

        // an out-of-range radix (<2 or >36) yields invalid results on both sides
        System.out.println("bad radix digit=" + Character.digit('1', 1));
        System.out.println("bad radix forDigit is nul: " + (Character.forDigit(15, 37) == '\u0000'));

        // case-insensitive: 'F' parses the same as 'f'
        System.out.println("upper F=" + Character.digit('F', 16));
    }
}

What the demo converts

Character.digit turns a char into its numeric value under a radix: f is 15 in radix 16 and 9 is 9, but the same f under radix 10 is not a digit, so the call returns -1 rather than throwing. forDigit runs the other way, mapping 15 back to its radix-16 char.

Both directions guard the radix itself: digit with radix 1 returns -1, and forDigit with radix 37 returns the NUL character, which the demo compares against the \u0000 escape. Uppercase F parses to the same 15, confirming case-insensitivity.

Practical notes

  • -1 and \u0000 are the invalid markers, not exceptions.
  • The radix must stay between 2 and Character.MAX_RADIX (36).

Interactive Tools for This Topic

FAQ

What does digit return for an invalid character?
-1, the invalid marker; the demo prints dec f=-1 because f has no value under radix 10, and no exception is thrown.