Java Program to Print the ASCII Value of a Character
ASCII (American Standard Code for Information Interchange) gives every basic character a number from 0 to 127. For example, 'A' is 65, 'a' is 97, '0' is 48 and a space is 32.
A Java char is stored as a number (its Unicode value, which matches ASCII for these characters), so finding the ASCII value is just a matter of reading the char as an int.
1. ASCII Value Using Assignment and Casting
Assigning a char to an int variable converts it automatically (implicit widening). You can also cast explicitly with (int).
public class AsciiValue {
public static void main(String[] args) {
char ch = 's';
int ascii = ch; // implicit conversion
int castAscii = (int) ch; // explicit cast
System.out.println("The ASCII value of " + ch + " is: " + ascii);
System.out.println("The ASCII value of " + ch + " is: " + castAscii);
}
}
The ASCII value of s is: 115 The ASCII value of s is: 115
2. ASCII Value with User Input
import java.util.Scanner;
public class AsciiValueInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
scanner.close();
System.out.println("The ASCII value of " + ch + " is: " + (int) ch);
}
}
Enter a character: G The ASCII value of G is: 71
3. ASCII Values of Every Character in a String
toCharArray() turns a string into an array of characters, which a loop can process one by one.
public class AsciiValuesOfString {
public static void main(String[] args) {
String text = "SMILE";
System.out.println("String: " + text);
for (char ch : text.toCharArray()) {
System.out.println(ch + " -> " + (int) ch);
}
}
}
String: SMILE S -> 83 M -> 77 I -> 73 L -> 76 E -> 69
4. Character from an ASCII Value
The conversion also works the other way: casting an int to char gives the character with that code. This program prints the codes 65 to 70.
public class CharFromAscii {
public static void main(String[] args) {
for (int code = 65; code <= 70; code++) {
System.out.println(code + " -> " + (char) code);
}
}
}
65 -> A 66 -> B 67 -> C 68 -> D 69 -> E 70 -> F
5. Summary
- Every character has a numeric code; in ASCII,
'A'is 65 and'a'is 97. - Assign a
charto anint, or cast with(int), to get its value. - Cast an
intto(char)to get the character for a code. - Use
toCharArray()to print the values of every character in a string.