Write a program in Java to find the ASCII value of a Character:
ASCII or American Standard Code for Information Interchange is a character encoding standard to represent characters in computers. By using a 7-bit binary number, a character is defined. There are 128 possible characters. In decimal form, we can represent a character from 0 to 127.
We have two different ways to find the ASCII value of a character in Java:
-
We can assign the character variable to an integer variable. Since an integer variable can’t hold a character variable, it will keep the ASCII value of the assigned character.
-
Typecast the character to an integer.
The below program shows both of these ways:
class Main {
public static void main(String[] args) {
char c = 'b';
//1 : Assigning
int value = c;
System.out.println("Ascii : " + value);
//2 : Typecasting
System.out.println("Ascii : " + (int) c);
}
}
Get it on Github
Output :
Ascii : 98
Ascii : 98
The advantage of typecasting is that you don’t need to create another integer variable.
Example 2: How to find the ASCII value of any user-input character:
The following program takes one character as input and prints its ASCII:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter a character: ");
char c = sc.next().charAt(0);
System.out.println("Ascii : "+(int)c);
}
}
}
Get it on Github
The program is self-explanatory. If you run it, it will ask you to enter a character and print its ASCII.
Similar tutorials :
- Java program to print the ASCII value of an integer
- Java Program to get all the permutation of a string
- Java program to remove element from an ArrayList of a specific index
- Java program to get the maximum number holder Student
- Java program to remove all white space from a string
- Java program to swap first and last character of a string