This Java example code demonstrates a simple Java program to find the ASCII value of a character and print the output to the screen.
Example:
public class PrintAsciiExample {
public static void main(String[] args) {
//Define the character whose ASCII value is to be found
char ch = 'G';
int ascii = ch; //Assign the character value to integer
//Print the output
System.out.println("The ASCII value of character '" + ch + "' is: " + ascii);
//Casting (character to integer)
int castAscii = (int) ch;
//Print the output
System.out.println("The ASCII value of character '" + ch + "' is: " + castAscii);
}
}
Program Output:
The ASCII value of 'G' is: 71 The ASCII value of 'G' is: 71
The above Java program shows two ways to print the ASCII value of a character:
- First, a character is defined using single quotes and assigned to an integer; In this way, Java automatically converts the character value to an ASCII value.
- Next, we cast the character
ch
variable to an integer using(int)
. Casting is the way of converting a variable type to another type.