Java Character Digit Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn about the digit() method provided by the Character class in Java. This method of the Character class is used to convert a character to its numeric value based on the provided radix.

Creating the Java file

Create a new Java file named CharacterDigit.java in the ~/project directory by executing the following command in the terminal.

touch ~/project/CharacterDigit.java

Writing the Java code

Add the following code to the CharacterDigit.java file to use the digit() method to convert a character to its numeric value.

import java.util.Scanner;
import java.lang.Character;

public class CharacterDigit {

    public static void main(String[] args) {

        try {
            // Step 2.1: Getting character codepoint and radix from the user
            System.out.print("Enter character codepoint value:");
            Scanner sc = new Scanner(System.in);
            int codePoint = sc.nextInt();
            System.out.print("Enter radix:");
            int radix = sc.nextInt();

            // Step 2.2: Converting character to its numeric value based on radix
            int digit = Character.digit(codePoint, radix);

            // Step 2.3: Displaying the result to the user
            System.out.println("The numeric value is: " + digit);
        } catch (Exception e) {
            System.out.println("Invalid input");
        }
    }
}

Compiling and Running the Java code

Compile the CharacterDigit.java file by executing the following command in the terminal.

javac ~/project/CharacterDigit.java

After a successful compilation, execute the following command to run the Java program:

java -cp ~/project CharacterDigit

You will see a prompt asking you to enter the character codepoint value and radix. Enter the desired values and press enter. The program will convert the entered character to its numeric value based on the radix provided.

Summary

In this lab, you learned how to use the digit() method provided by the Character class in Java. This method is used to convert a character to its numeric value based on the provided radix. You also learned the steps required to create a Java program to use this method and how to run and test it in the terminal.

Other Java Tutorials you may like