How to convert ASCII code (0-255) to its corresponding character?
To convert an ASCII code (0-255) to its corresponding character in Java, you can use the char
data type and cast the ASCII code to it. Here's an example of how to do this:
public class Main {
public static void main(String[] args) {
int asciiCode = 65;
char character = (char) asciiCode;
System.out.println(character); // Outputs: 'A'
}
}
The char
data type in Java represents a single Unicode character, and it can hold a value from 0 to 65,535. ASCII codes are a subset of Unicode, with codes ranging from 0 to 127, so they can be represented by the char
data type as well.
You can use a loop to convert a range of ASCII codes to characters, like this:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 256; i++) {
char character = (char) i;
System.out.println(i + ": " + character);
}
}
}
This will print the ASCII code and its corresponding character for all ASCII codes from 0 to 255.