Java Program to Print ASCII Values



For a given character, say "ch", write a Java program to print its ASCII value. We can find the ASCII value of any character by assigning it to an integer value and printing that integer value.

The term ASCII stands for American Standard Code for Information Interchange. There are 128 standard ASCII codes, each of which can be represented by a 7-digit binary number: 0000000 through 1111111. Extended ASCII adds an additional 128 characters that vary between computers, programs and fonts.

Example Scenario:

Input: character = s;
Output: ascii_value = 115

Example 1

In this example, we are printing the ASCII value of the character "s".

public class AsciiValue{
   public static void main(String[] args){
      char my_input;
      my_input = 's';
      System.out.println("The character has been defined as " +my_input);
      int ascii_value = my_input;
      System.out.println("The ASCII value of " + my_input + " is: " + ascii_value);
   }
}

Output

The character has been defined as s
The ASCII value of s is: 115

Example 2

In this Java program, we are printing ASCII value of English letters A to Z.

public class AsciiValue {
   public static void main(String[] args) {
      for(char ch = 'A'; ch <= 'Z'; ch++) {
         int ascii_value = ch;
         System.out.print(ch + " = " + ascii_value + ", ");
      }
   }
}

Output

A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, 
G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, 
M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, 
S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, 
Y = 89, Z = 90,

Example 3

Type-Casting is a process of converting a given datatype into another. Here, we use type-casting to print ASCII value of given character.

public class AsciiValue {
   public static void main(String[] args) {
      char my_input;
      my_input = 'd';
      System.out.println("The ASCII value is: " + (int)my_input);
   }
}

Output

The ASCII value is: 100
Updated on: 2024-09-13T16:14:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements