Introduction
Java Program to Find ASCII Value of a Character
A Java program to find and print the ASCII value of a character.
Problem Description
Write a Java program that takes a character as input (or uses a hardcoded character) and prints its ASCII value.
Code
public class AsciiValue {
public static void main(String[] args) {
char ch = 'a';
int ascii = ch;
// You can also cast char to int
int castAscii = (int) ch;
System.out.println("The ASCII value of " + ch + " is: " + ascii);
System.out.println("The ASCII value of " + ch + " is: " + castAscii);
}
}Output
The ASCII value of a is: 97
The ASCII value of a is: 97Explanation
char ch = 'a';: Declares a character variablechand assigns it the value 'a'.int ascii = ch;: Assigns the character value to an integer variable. Java automatically promoteschartoint, which results in the ASCII value.(int) ch: Explicitly casts the character to an integer, which also yields the ASCII value.
Try Yourself
Test your understanding of characters and ASCII values.
- Find Value of 'Z': Change the character to 'Z' and find its ASCII value.
- Digit ASCII: Find the ASCII value of the character '9'. Is it the number 9?
- Reverse It: Create an integer variable
int n = 66;and cast it tochar. What letter do you get? - Math with Char: What happens if you do
System.out.println('a' + 1);? Try it. - Brain Twister: Find the ASCII value of the space character
' '.
Java Program to Multiply Two Numbers
In this program, you'll learn to store and multiply two integer numbers in Java. After multiplication, the final value is displayed on the screen.
Java Program to Display Size of Different Data Types
A Java program to display the size (in bits and bytes) of primitive data types.
