Java.lang.Character.digit() Method


Advertisements


Description

The java.lang.Character.digit(char ch, int radix) returns the numeric value of the character ch in the specified radix.

If the radix is not in the range MIN_RADIX ≤ radix ≤ MAX_RADIX or if the value of ch is not a valid digit in the specified radix, -1 is returned. A character is a valid digit if at least one of the following is true −

  • The method isDigit is true of the character and the Unicode decimal digit value of the character (or its single-character decomposition) is less than the specified radix. In this case the decimal digit value is returned.

  • The character is one of the uppercase Latin letters 'A' through 'Z' and its code is less than radix + 'A' − 10. In this case, ch − 'A' + 10 is returned.

  • The character is one of the lowercase Latin letters 'a' through 'z' and its code is less than radix + 'a' − 10. In this case, ch − 'a' + 10 is returned.

  • The character is one of the fullwidth uppercase Latin letters A ('\uFF21') through Z ('\uFF3A') and its code is less than radix + '\uFF21' − 10. In this case, ch − '\uFF21' + 10 is returned.

  • The character is one of the fullwidth lowercase Latin letters a ('\uFF41') through z ('\uFF5A') and its code is less than radix + '\uFF41' − 10. In this case, ch − '\uFF41' + 10 is returned.

Declaration

Following is the declaration for java.lang.Character.digit() method

public static int digit(char ch, int radix)

Parameters

  • ch − the character to be converted

  • radix − the radix

Return Value

This method returns the numeric value represented by the character in the specified radix.

Exception

NA

Example

The following example shows the usage of lang.Character.digit() method.

package com.tutorialspoint;

import java.lang.*;

public class CharacterDemo {

   public static void main(String[] args) {

      // create 2 character primitives ch1, ch2
      char ch1, ch2;

      // assign values to ch1, ch2
      ch1 = '9';
      ch2 = '5';

      // create 2 int primitives i1, i2
      int i1, i2;

      // assign numeric value of ch1, ch2 to i1, i2 using radix
      i1 = Character.digit(ch1, 2);
      i2 = Character.digit(ch2, 10);

      String str1 = "Numeric value of " + ch1 + " in radix 2 is " + i1;
      String str2 = "Numeric value of " + ch2 + " in radix 10 is " + i2;

      // print i1, i2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

Let us compile and run the above program, this will produce the following result −

Numeric value of 9 in radix 2 is -1
Numeric value of 5 in radix 10 is 5

java_lang_character.htm

Advertisements