In this tutorial, you will learn how to convert a char
to an int
in Java. We’ll cover methods to retrieve both the ASCII value and the numeric value of a char
, with examples to illustrate each approach.
Java – Convert char to int
Converting char to int in Java – In Java, a char
represents a single 16-bit Unicode character, while an int
is a 32-bit signed integer. Converting a char
to an int
can mean retrieving its ASCII (or Unicode) value or obtaining its numeric value if it represents a digit.
Method 1: Getting the ASCII Value of a char
In Java, you can get the ASCII (or Unicode) value of a char
by casting it to an int
. This method works for all characters and will return the corresponding ASCII or Unicode integer value.
Example of Getting ASCII Value
public class CharToIntExample {
public static void main(String[] args) {
char charVal = 'A';
int asciiValue = (int) charVal; // Get ASCII value by casting
System.out.println("Char value: " + charVal);
System.out.println("ASCII value: " + asciiValue);
}
}
Output
Char value: A
ASCII value: 65
In this example, the char
'A'
has an ASCII value of 65
, which is retrieved by casting the char
to an int
.
Method 2: Getting the Numeric Value of a Digit char
If the char
represents a numeric digit (e.g., '1'
, '2'
), you can use Character.getNumericValue()
to obtain its integer representation. This method returns the numeric value of a Unicode character.
Example of Getting Numeric Value
public class CharToIntExample {
public static void main(String[] args) {
char charVal = '5';
int numericValue = Character.getNumericValue(charVal); // Get numeric value
System.out.println("Char value: " + charVal);
System.out.println("Numeric value: " + numericValue);
}
}
Output
Char value: 5
Numeric value: 5
In this example, the char
'5'
is converted to the integer 5
using Character.getNumericValue()
.
Conclusion
Converting a char
to an int
in Java can be done in two ways: by casting to get the ASCII value or by using Character.getNumericValue()
to obtain the numeric representation of a digit.