Find the ASCII value of a character in Java
Understanding ASCII Values
ASCII (American Standard Code for Information Interchange) assigns numerical values to characters. For example, 'A' has an ASCII value of 65.
We will explore three different methods to find the ASCII value of a character in Java.
Method 1: Using Type Casting
This method prints the ASCII value of a character using type casting.
import java.util.Scanner; public class ASCIIValue { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a character: "); char ch = scanner.next().charAt(0); System.out.println("ASCII value of " + ch + " is " + (int) ch); scanner.close(); } }
Output: ASCII value of A is 65
Method 2: Using a Function
This method uses a function to return the ASCII value of a character.
import java.util.Scanner; public class ASCIIValueFunction { public static int getASCII(char ch) { return (int) ch; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a character: "); char ch = scanner.next().charAt(0); System.out.println("ASCII value of " + ch + " is " + getASCII(ch)); scanner.close(); } }
Output: ASCII value of z is 122
Method 3: Using a Wrapper Class
This method uses the Character wrapper class to find the ASCII value.
import java.util.Scanner; public class ASCIIValueWrapper { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a character: "); char ch = scanner.next().charAt(0); Integer asciiValue = Character.getNumericValue(ch) + 48; System.out.println("ASCII value of " + ch + " is " + asciiValue); scanner.close(); } }
Output: ASCII value of B is 66