top of page

7)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 a pattern in Java.

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.

back.png

public class PrintAsciiValueExample1   

{  

public static void main(String[] args)   

{  

// character whose ASCII value to be found  

char ch1 = 'a';  

char ch2 = 'b';  

// variable that stores the integer value of the character  

int asciivalue1 = ch1;  

int asciivalue2 = ch2;  

System.out.println("The ASCII value of " + ch1 + " is: " + asciivalue1);  

System.out.println("The ASCII value of " + ch2 + " is: " + asciivalue2);  

}  

}  

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.

back.png

public class PrintAsciiValueExample3   

{  

public static void main(String[] args)   

{  

//characters whose ASCII value to be found  

char ch1 = 'a';  

char ch2 = 'b';  

//casting or converting a charter into int type  

int ascii1 = (int) ch1;  

int ascii2 = (int) ch2;  

System.out.println("The ASCII value of " + ch1 + " is: " + ascii1);  

System.out.println("The ASCII value of " + ch1 + " is: " + ascii2);  

}  

}  

bottom of page