Javatpoint Logo
Javatpoint Logo

How to Print ASCII Value in Java

ASCII acronym for American Standard Code for Information Interchange. It is a 7-bit character set contains 128 (0 to 127) characters. It represents the numerical value of a character. For example, the ASCII value of A is 65.

In this section, we will learn how to print ASCII value or code through a Java program.

There are two ways to print ASCII value in Java:

  • Assigning a Variable to the int Variable
  • Using Type-Casting

Assigning a Variable to the int Variable

To print the ASCII value of a character, we need not use any method or class. Java internally converts the character value to an ASCII value.

Let's find the ASCII value of a character through a Java program.

In the following program, we have assigned two characters a and b in the ch1 and ch2 variables, respectively. To find the ASCII value of a and b, we have assigned ch1 and ch2 variables to the integer variables asciivalue1 and asciivalue2, respectively. Finally, we have printed the variable asciivalue1 and asciivalue2 in which ASCII values of the characters are stored.

PrintAsciiValueExample1.java

Output:

The ASCII value of a is: 97
The ASCII value of b is: 98

Another way to write the above program is:

PrintAsciiValueExample2.java

Output:

The ASCII value of a is: 97
The ASCII value of b is: 98

Similarly, we can print the ASCII value of other characters (A, B, C, …., Z) and symbols (!, @, $, *, etc.).

Using Type-Casting

Type-casting is a way to cast a variable into another datatype.

In the following program, we have declared two variables ch1 and ch2 of type char having the character a and b, respectively. In the next two lines, we have cast char type to int type using (int). After executing these two lines, the variable ch1 and ch2 are converted to an int variable ascii1 and ascii2, respectively.

Finally, we have printed the variable ascii1 and ascii2 in which ASCII values of the characters are stored.

PrintAsciiValueExample3.java

Output:

The ASCII value of a is: 97
The ASCII value of b is: 98

If we do not want to assign character, we can also take a character from the user.

PrintAsciiValueExample4.java

Output 1:

Enter a character: P
ASCII value of P is: 80

Output 2:

Enter a character: G
ASCII value of G is: 71

The following program prints the ASCII value (0 to 255) of all the characters. In the output, we have shown a few values.

AsciiValueOfAllChracters.java

Output:

How to Print ASCII Value in Java

If we want to print the ASCII value of all the alphabets (A to Z), we can set the values in the loop and print them.

AsciiValueAtoZ.java

Output:

How to Print ASCII Value in Java

Similarly, we can print the ASCII value of a to z by changing the loop in the above code.


Next TopicJava Tutorial




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA