How to convert Char to Int in Java?

Last updated on Sep 06,2024 4.6K Views

How to convert Char to Int in Java?

edureka.co

In Java, the value contained in one data type can be converted to another data type based on conversion requirements, the same holds true for char to int conversion. Converting a char to an int is equivalent to finding the ASCII value of the given character. In this article on “Convert Char to Int in Java”, we will learn how to convert a char to int with the help of examples. 

The topics discussed in this article are:

What are Data types?

Data types are the storage containers that store the value of a particular type like integers, chars, floating values, Boolean values, etc. A data type specifies the type of value a variable has and the type of relational, mathematical or logical operations that can be applied to it without causing an error. 

The choice of data types for a particular variable depends on multiple factors. In most cases, the decision is intuitive. For example,

Java char to int: Getting ASCII value

Filename: CharToIntExample.java

Code:

public static void main(String args[]){  
char c='Z';  
char c1='9';  
int a=c;  
int b=c1;  
System.out.println(a);  
System.out.println(b);  
}}  

Compile by : javac CharToIntExample.java
Run by : java CharToIntExample

Output

       

Java char to int Example: Character.getNumericValue()

Filename: CharToIntExample1.java

Code:

public class CharToIntExample1{  
public static void main(String args[]){  
char c='9';  
int a=Character.getNumericValue(c);  
System.out.println(a);  
}}

Compile by: javac CharToIntExample1.java
Run by: java CharToIntExample1

Output:

Java char to int Example: String.valueOf() :

Filename: CharToIntExample2.java

Code:

public class CharToIntExample2{  
public static void main(String args[]){  
char c='8';  
int a=Integer.parseInt(String.valueOf(c));  
System.out.println(a);  
}}  

Compile by: javac CharToIntExample2.java

Run by: java CharToIntExample2

Output:

 

With this, we come to an end of this article. I hope it added value to your knowledge.

If you are interested to learn more about Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework