Convert Character to ASCII Numeric Value in Java

Convert chartacter to ascii in java

In this post, we will see How to convert Character to ASCII Numeric Value in Java.
There are multiple ways to convert Character to ASCII Numeric Value in Java

By casting char to int

You can simply get char from String using charAt() and cast it to int.
Here is an example:

Output:

Ascii value of e is: 101

You can even directly assign char to int, but it is good idea to explicitly cast it for readabiliy.
You can change highlighted code to below line and program will still work:

Using toCharArray()

You can simply use index with toCharArray() to get ASCII value of character in the String.
Here is an example:

Output:

Ascii value of e is: 101

Using String’s getBytes()

You can convert String to byte array using getBytes(StandardCharsets.US_ASCII) and this byte array will contain character’s ASCII values. You can access individual value by accessing byte array by index.
Here is an example:

Output:

Ascii value of e is: 101ASCII values for all characters are:72 101 108 108 111

Using String’s char() [Java 9+]

You can convert String to IntStream using String’s chars() method, use boxed() to convert it to Stream of wrapper type Integer and collect to the list. Result list will contain all the ascii value of the characters and you can use index to access individual ASCII value of character.
Here is an example:

Output:

ASCII values for all characters are:72 101 108 108 111

Convert a String of letters to an int of corresponding ascii

If you want to convert entire String into concatenated ASCII value of int type, you can create StringBuilder from String’s ASCII values and convert it to BigInteger.
Here is an example:

Output:

72101108108111

That’s all about Convert Character to ASCII in Java

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *