Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
ascii
communitycreator

How to get the ASCII value of a character in Java

abhilash

What are ASCII values?

ASCII assigns letters, numbers, characters, and symbols a slot in the 256 available slots in the 8-bit code.

For example:

Character ASCII value
a 97
b 98
A 65
B 66

Cast char to int

Cast a character from the char data type to the int data type to give the ASCII value of the character.

Code

In the code below, we assign the character to an int variable to convert it to its ASCII value.

public class Main {
    public static void main(String[] args) {
        char ch = 'a';
        int as_chi = ch;
        System.out.println("ASCII value of " + ch + " is - " + as_chi);
    }
}

In the code below, we print the ASCII value of every character in a string by casting it to int.

public class Main {
    public static void main(String[] args) {
        String alphabets = "abcdjfre";
        for(int i=0;i<alphabets.length();i++){
            char ch = alphabets.charAt(i);
            System.out.println("ASCII value of " + ch + " is - " + (int)ch);
        }
    }
}

RELATED TAGS

java
ascii
communitycreator
RELATED COURSES

View all Courses

Keep Exploring