示例:查找字符的ASCII值
public class AsciiValue {
public static void main(String[] args) {
char ch = 'a';
int ascii = ch;
// You can also cast char to int
int castAscii = (int) ch;
System.out.println("The ASCII value of " + ch + " is: " + ascii);
System.out.println("The ASCII value of " + ch + " is: " + castAscii);
}
}
输出
The ASCII value of a is: 97 The ASCII value of a is: 97
在上面的程序中,字符a
存储在char
变量ch中。就像用双引号(" ")
声明字符串一样,我们用单引号(' ')
声明字符。
现在,为了找到ch的ASCII值,我们只需将ch赋值给int
变量ascii。在内部,Java会将字符值转换为ASCII值。
我们也可以使用(int)
将字符ch 类型转换为整数。简单来说,类型转换是将一个变量从一种类型转换为另一种类型,这里是将char
变量ch转换为int
变量castAscii。
最后,我们使用println()
函数打印ASCII值。