How to Get Ascii Value of Char in Java
In this tutorial we will learn the different ways to convert values of primitive data type char to int in Java along with FAQs and examples:
We will be covering the use of the following methods provided by different Java classes for converting character to int :
- Implicit type casting ( getting ASCII values )
- getNumericValue()
- parseInt() with String.valueOf()
- Subtracting '0'
=> Check Here To See A-Z Of Java Training Tutorials
What You Will Learn:
- Convert Char To int In Java
- #1) Using Implicit Type Cast i.e. Getting ASCII Value Of The Character
- #2) Using Character.getNumericValue() Method
- #3) Using Integer.parseInt() And String.ValueOf() Method
- #4) Convert Char To int In Java By Subtracting '0'
- FAQs Regarding Char To Int Java
- Conclusion
- Recommended Reading
Convert Char To int In Java
Java has primitive data types like int, char, long, float, etc. In some scenarios, it is required to perform operations on numeric values, where variable values are specified in the data type of char.
In such cases, we have to first convert these character values to numeric values i.e. int values, and then perform the desired actions, calculations on these.
For example, in some software systems, certain operations need to be performed, or some decisions must be taken based on the customer ratings received in the customer feedback form which comes as the character data type.
In such cases, these values need to be first converted to int data type to perform numeric operations on these values further. Java provides various methods to convert character to an int value. Let us have look at these methods in detail.
#1) Using Implicit Type Cast i.e. Getting ASCII Value Of The Character
In Java, if you assign a smaller data type value to a variable of the compatible larger data type variable, then the value gets automatically promoted i.e. implicitly gets typecast to a variable of the larger data type.
For Example, if we assign a variable of type int to a variable of type long, then the int value automatically gets typecast to data type long.
Implicit type casting happens for the 'char' data type variable as well i.e. when we assign the following char variable value to the variable 'int' data type, then the char variable value gets converted to an int automatically by the compiler.
For example,
char a = '1';
int b = a ;
Here char 'a' gets implicitly typecast to the int data type.
If we print the value of 'b', then you will see console prints '49'. This is because when we assign char variable value 'a' to int variable 'b', we actually retrieve the ASCII value of '1' which is '49'.
In the following sample Java program, let's see how to convert character to int through implicit typecast i.e. getting ASCII value of char variable.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to int Java program * using Implicit type casting i.e. ASCII values * * @author * */ public class CharIntDemo1 { public static void main(String[] args) { // Assign character 'P' to char variable char1 char char1 = 'P'; // Assign character 'p' to char variable char2 char char2 = 'p'; // Assign character '2' to char variable char3 char char3 = '2'; // Assign character '@' to char variable char4 char char4 = '@'; // Assign character char1 to int variable int1 int int1 = char1; // Assign character char2 to int variable int2 int int2 = char2; // Assign character char3 to int variable int3 int int3 = char3; // Assign character char2 to int variable int4 int int4 = char4; //print ASCII int value of char System.out.println("ASCII value of "+char1+" -->"+int1); System.out.println("ASCII value of "+char2+" -->"+int2); System.out.println("ASCII value of "+char3+" -->"+int3); System.out.println("ASCII value of "+char4+" -->"+int4); } }
Here is the program Output:
ASCII value of P –>80
ASCII value of p –>112
ASCII value of 2 –>50
ASCII value of @ –>64
In the above program, we can see the ASCII values of different char variable values as follows:
ASCII value of P –>80
ASCII value of p –>112
The difference in values for 'P' and 'p' is because ASCII values are different for upper case letters and small case letters.
Similarly, we get ASCII values for numeric values and special character as well as follows:
ASCII value of 2 –>50
ASCII value of @ –>64
#2) Using Character.getNumericValue() Method
The Character class has static overloading methods of getNumericValue(). This method returns a value of data type int represented by a specified Unicode character.
Here is the method signature of the getNumericValue() method for char data type:
public static int getNumericValue(char ch)
This static method receives an argument of data type char and returns the data type int value that argument 'ch' represents.
For example, the character '\u216C' returns an integer with a value of 50.
Parameters:
ch: This is a character that needs to be converted to int.
Returns:
This method returns the numeric value of 'ch', as a non-negative value of data type int. This method returns -2 if 'ch' has a numeric value that is not a non-negative integer. Returns -1 if 'ch' does not have a numeric value.
Let's understand the use of this Character.getNumericValue() method to convert character to an int value.
Let's consider the scenario wherein one of the bank software systems, where gender is specified in data type 'char' and based on the gender code some decision needs to be made like assigning interest rate.
For this, the gender code needs to be converted from char to int data type. This conversion is done using the Character.getNumericValue() method in the sample program below.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to int Java program * using Character.getNumericValue() * * @author * */ public class CharIntDemo2 { public static void main(String[] args) { // Assign character '1' to char variable char1 char gender = '1'; //Send gender as an argument to getNumericValue() method // to parse it to int value int genderCode = Character.getNumericValue(gender); // Expected to print int value 1 System.out.println("genderCode--->"+genderCode); double interestRate = 6.50; double specialInterestRate = 7; switch (genderCode) { case 0 ://genderCode 0 is for Gender Male System.out.println("Welcome ,our bank is offering attractive interest rate on Fixed deposits :"+ interestRate +"%"); break; case 1 ://genderCode 1 is for Gender Female System.out.println(" Welcome, our bank is offering special interest rate on Fixed deposits "+ "for our women customers:"+specialInterestRate+"% ."+"\n"+" Hurry up, this offer is valid for limited period only."); break; default : System.out.println("Please enter valid gender code "); } } }
Here is the program Output:
genderCode—>1
Welcome, our bank is offering special interest rate on Fixed deposits for our women customers:7.0% .
Hurry up, this offer is valid for limited period only.
So, in the above program, we are converting char variable gender value to int value to get the int value in variable genderCode.
char gender = '1';
int genderCode = Character.getNumericValue(gender);
So, when we print on console, System. out .println("genderCode—>"+genderCode); then we see the int value on the console as below:
genderCode—>1
The same variable value is passed to switch case loop switch (genderCode) for further decision making.
#3) Using Integer.parseInt() And String.ValueOf() Method
This static parseInt() method is provided by the wrapper class Integer class.
Here is the method signature of Integer.parseInt():
public static int parseInt(String str) throws NumberFormatException
This method parses the String argument, it considers String as a signed decimal integer. The String argument's all characters must be decimal digits. The only exception is that the first character is allowed to be an ASCII minus sign '-' and plus sign '+' for an indication of a negative value and positive value respectively.
Here, the 'str' parameter is a String having the int representation to be parsed and returns the integer value represented by the argument in decimal. When the String does not contain a parsable integer, then the method throws an Exception NumberFormatException
As seen in the method signature for parseInt(String str), the argument to be passed to parseInt() method is of String data type. So, it is required to convert a char value to String first and then pass this String value to parseInt() method. For this the String.valueOf() method is used .
valueOf () is a static overloading method of String class that is used to convert arguments of primitive data types like int, float to String data type.
public static String valueOf(int i)
This static method receives an argument of data type int and returns the string representation of the int argument.
Parameters:
i: This is an integer.
Returns:
The string representation of the int argument.
So , we are using a combination of Integer.parseInt() and String.valueOf() method. Let's see the use of these methods in the following sample program. This sample program [1] First converts the customer rating value of character data type to integer and [2] then prints the appropriate message on the console using the if-else statement.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to int Java program * using Integer.parseInt() and String.valueOf() methods * * @author * */ public class CharIntDemo3 { public static void main(String[] args) { // Assign character '7' to char variable customerRatingsCode char customerRatingsCode = '7'; //Send customerRatingsCode as an argument to String.valueOf method //to parse it to String value String customerRatingsStr = String.valueOf(customerRatingsCode); System.out.println("customerRatings String value --->"+customerRatingsStr); // Expected to print String value 7 //Send customerRatingsStr as an argument to Integer.parseInt method //to parse it to int value int customerRatings = Integer.parseInt(customerRatingsStr); System.out.println("customerRatings int value --->"+customerRatings); // Expected to print int value 7 if (customerRatings>=7) { System.out.println("Congratulations! Our customer is very happy with our services."); }else if (customerRatings>=5) { System.out.println("Good , Our customer is satisfied with our services."); }else if(customerRatings>=0) { System.out.println("Well, you really need to work hard to make our customers happy with our services."); }else { System.out.println("Please enter valid ratings value."); } } }
Here is the program Output:
customerRatings String value —>7
customerRatings int value —>7
Congratulations! Our customer is very happy with our services.
In the above sample code, we have used the String.valueOf() method to convert character to a value of String data type.
char customerRatingsCode = '7'; String customerRatingsStr = String.valueOf(customerRatingsCode);
Now, this String value is converted to data type int using the Integer.parseInt() method by passing customerRatingsStr as an argument.
int customerRatings = Integer.parseInt(customerRatingsStr); System.out.println("customerRatings int value --->"+customerRatings); // Expected to print int value 7
This int value customerRating is used further in the if-else statement for comparing and printing the required message on the console.
#4) Convert Char To int In Java By Subtracting '0'
We have seen converting character to int using implicit typecasting. This returns the ASCII value of the character. E.g. ASCII value of 'P' returns 80 and the ASCII value of '2' returns 50.
However, to retrieve the int value for '2' as 2, the character ASCII value of '0' needs to be subtracted from the character. E.g. To retrieve int 2 from character '2',
int intValue = '2'- '0'; System.out.println("intValue?"+intValue); This will print intValue->2.
Note: This is useful to get int values for numeric value characters only i.e. 1, 2, etc., and not useful with text values like 'a', 'B' etc. as it will just return the difference between the ASCII values of '0' and that character.
Let's have a look at the sample program to use this method of subtracting the ASCII value of Zero i.e. '0' from the character ASCII value.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to int Java program * using ASCII values by subtracting ASCII value of '0'from ASCII value of char * * @author * */ public class CharIntDemo4 { public static void main(String[] args) { // Assign character '0' to char variable char1 char char1 = '0'; // Assign character '1' to char variable char2 char char2 = '1'; // Assign character '7' to char variable char3 char char3 = '7'; // Assign character 'a' to char variable char4 char char4 = 'a'; //Get ASCII value of '0' int int0 = char1; System.out.println("ASCII value of 0 --->"+int0); int0 = char2; System.out.println("ASCII value of 1 --->"+int0); // Get int value by finding the difference of the ASCII value of char1 and ASCII value of 0. int int1 = char1 - '0'; // Get int value by finding the difference of the ASCII value of char2 and ASCII value of 0. int int2 = char2 - '0'; // Get int value by finding the difference of the ASCII value of char3 and ASCII value of 0. int int3 = char3 - '0'; // Get int value by finding the difference of the ASCII value of char4 and ASCII value of 0. int int4 = char4 - '0'; //print ASCII int value of char System.out.println("Integer value of "+char1+" -->"+int1); System.out.println("Integer value of "+char2+" -->"+int2); System.out.println("Integer value of "+char3+" -->"+int3); System.out.println("Integer value of "+char4+" -->"+int4); } }
Here is the program Output:
ASCII value of 0 —>48
ASCII value of 1 —>49
Integer value of 0 –>0
Integer value of 1 –>1
Integer value of 7 –>7
Integer value of a –>49
In the above program, if we assign char '0' and '1' to the int data type value, we will get ASCII values of these characters due to implicit conversion. So, when we print these values as seen in the below statements:
int int0 = char1; System.out.println("ASCII value of 0 --->"+int0); int0 = char2; System.out.println("ASCII value of 1 --->"+int0);
We will get the output as:
ASCII value of 0 —>48
ASCII value of 1 —>49
So, to get an integer value representing the same value as that of char, we are subtracting the ASCII value of '0' from the characters representing numeric values.
int int2 = char2 - '0'; .
Here, we are subtracting ASCII values of '0' from the '1' ASCII value.
i.e. 49-48 =1 . Hence, when we print on console char2
System.out.println("Integer value of "+char2+" –>"+int2);
We get the output as:
Integer value of 1 –>1
With this, we have covered the various ways of converting Java character to an integer value with the help of sample programs. So, to convert character to int in Java, any of the methods covered in the above sample codes can be used in your Java program.
Now, let's have look at some of the frequently asked questions about the Java character to int conversion.
FAQs Regarding Char To Int Java
Q #1) How do I convert a char to an int?
Answer:
In Java, char can be converted to int value using the following methods:
- Implicit type casting ( getting ASCII values )
- Character.getNumericValue()
- Integer.parseInt() with String.valueOf()
- Subtracting '0'
Q #2) What is a char in Java?
Answer: The char data type is a Java primitive data type having a single 16-bit Unicode character. The value is assigned as a single character enclosed with a single quote ''. For Example, char a = 'A' or char a = '1' etc.
Q #3) How do you initialize a char in Java?
Answer: char variable is initialized by assigning a single character enclosed in single quotes i.e. ''. For example, char x = 'b' , char x = '@' , char x = '3' etc.
Q #4) What is the int value of char A?
Answer: If char 'A' is assigned to the int variable, then char will be implicitly promoted to int and if the value is printed, it will return ASCII value of character 'A' which is 65.
For example,
int x= 'A'; System.out.println(x);
So, this will print 65 on the console.
Conclusion
In this tutorial, we have seen the following ways to convert values of Java data type char to int.
- Implicit type casting ( getting ASCII values )
- Character.getNumericValue()
- Integer.parseInt() with String.valueOf()
- Subtracting '0'
We have covered each of these ways in detail and demonstrated the use of each method with the help of a sample Java program.
=> Check ALL Java Tutorials Here
How to Get Ascii Value of Char in Java
Source: https://www.softwaretestinghelp.com/convert-char-to-int-in-java/