java.lang.Character forDigit(int digit, int radix)

Description

The Character.forDigit(int digit, int radix) java method determines the character representation for a specific digit in the specified radix. If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character (‘u0000’) is returned.

The radix argument is valid if it is greater than or equal to MIN_RADIX and less than or equal to MAX_RADIX. The digit argument is valid if 0 <= digit < radix.

If the digit is less than 10, then ‘0’ + digit is returned. Otherwise, the value ‘a’ + digit – 10 is returned.

The forDigit(int digit, int radix) method of Character class is static thus it should be accessed statically which means the we would be calling this method in this format:

Character.forDigit(int digit, int radix)

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java forDigit() method non statically.

Method Syntax

public static char forDigit(int digit, int radix)

Method Argument

Data Type Parameter Description
int digit the number to convert to a character.
int radix the radix.

Method Returns

The digit(char ch, int radix) method of Character class returns the numeric value represented by the character in the specified radix.

Compatibility

Requires Java 1.0 and up

Java Character forDigit(int digit, int radix) Example

Below is a simple java example on the usage of forDigit(int digit, int radix) method of Character class.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * This example source code demonstrates the use of 
 * forDigit(int digit, int radix) method of Character class.
 */

public class CharacterForDigitExample {

	public static void main(String[] args) {

		// Ask for user input
		System.out.print("Enter an input:");

		// use scanner to get the user input
		Scanner s = new Scanner(System.in);

		// get the user input
		int digit = s.nextInt();

		// ask for radix input
		System.out.print("Enter the radix:");

		// get the radix
		int radix = s.nextInt();

		// close the scanner object
		s.close();

		// get the character representation 
		// for a specific digit in the specified radix
		char result = Character.forDigit(digit, radix);
		
		// print the result
		System.out.println("digit '" + digit + "' using radix " 
				+ radix + " character representation is " + result);

	}

}

Sample Output

Below is the sample output when you run the above example.

java Character forDigit(int digit, int radix) example output