New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Java Character getNumericValue(char ch) Method

Java getNumericValue(char ch) method is a part of Character class. This method returns the int value of the specified. It returns -1 if the specified character does not have any int(numeric) value and -2 if the character has a numeric value that cannot be represented as a non-negative integer(for example a fraction or a decimal value).

Syntax:

public static int getNumericValue(char ch)  

Parameters:

The parameter passed is the character whose integer value is to be returned.

Returns:

Returns the numeric value of the specified character as a non-negative integer.

Example 1:

Here, the numerical non-negative int value of the characters is fetched by using getNumericValue() method.

public class StudyTonight 
{  
	public static void main(String[] args)
	{         
		char ch1 = 'A';  
		char ch2 = 'G';  
		char ch3 = 'M';  
		char ch4 = '7';  
		char ch5 = 'Q';      
		int r1 = Character.getNumericValue(ch1); //return int value for the specified character
		int r2 = Character.getNumericValue(ch2);  
		int r3 = Character.getNumericValue(ch3);  
		int r4 = Character.getNumericValue(ch4);
		int r5 = Character.getNumericValue(ch5);      
		System.out.println("The character " + ch1 + " has int value : " + r1);  
		System.out.println("The character " + ch2 + " has int value : " + r2);  
		System.out.println("The character " + ch3 + " has int value : " + r3);  
		System.out.println("The character " + ch4 + " has int value : " + r4);
		System.out.println("The character " + ch5 + " has int value : " + r5);      
	}
} 


The character A has int value : 10
The character G has int value : 16
The character M has int value : 22
The character 7 has int value : 7
The character Q has int value : 26

Example 2:

Here is a general example where the user can enter the input of his choice and get the desired output.

import java.util.Scanner;
public class StudyTonight 
{  
	public static void main(String[] args)
	{         
		try
		{
			System.out.println("Enter the character"); 
			Scanner sc = new Scanner(System.in);
			char ch = sc.next().charAt(0);      
			int r = Character.getNumericValue(ch);  
			System.out.println("The character " + ch + " has value : " + r);
		}
		catch(Exception e)
		{
			System.out.println("Invalid input");
		}
	}
} 


Enter the character
H
The character H has value : 17
************************************
Enter the character
4
The character 4 has value : 4

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.