Java int 转 char

2024年12月7日 | 阅读 6 分钟

在 Java 中,我们可以使用类型转换将 int 转换为 char。为了将较高数据类型转换为较低数据类型,我们需要执行类型转换。在这里,整数值的 ASCII 字符将存储在 char 变量中。

Java Convert int to char

要获取 char 变量中的实际值,我们可以将 '0' 加到 int 变量上。或者,我们可以使用 Character.forDigit() 方法。

Java int 转 char 示例:使用类型转换

让我们看一下在 Java 中将 long 转换为 int 的简单代码。

文件名:IntToCharExample1.java

输出

A

但是,如果我们存储 1,它将存储给定数字的 ASCII 字符,即标题开始,这是不可打印的。所以它不会在控制台打印任何内容。

文件名:IntToCharExample2.java

输出

1

如果我们向 int 变量添加 '0',它将返回 char 变量中的实际值。 '0' 的 ASCII 值为 48。所以,如果我们向 48 加 1,它就变成 49,等于 1。49 的 ASCII 字符是 1。

文件名:IntToCharExample3.java

输出

1

如果我们以单引号存储整数值,它会将实际字符存储在 char 变量中。

文件名:IntToCharExample4.java

输出

1

要获取实际值,我们还可以使用 Character.forDigit() 方法。

文件名:IntToCharExample5.java

输出

1

要获取十六进制值,请在 Character.forDigit() 方法中使用基数 16。

文件名:IntToCharExample6.java

输出

a

让我们看看其他一些将 int 转换为 char 的流行方法

方法 1:使用 switch case

文件名:IntToCharSwitchCase.java

输出

The integer 1 is converted to character: a
The integer 2 is converted to character: e
The integer 3 is converted to character: i
The integer 4 is converted to character: o
The integer 5 is converted to character: u

方法 2:使用类型转换概念

文件名:IntToCharTypeCasting.java

输出

The ASCII value 65 is converted to character: A
The ASCII value 66 is converted to character: B
The ASCII value 67 is converted to character: C
The ASCII value 97 is converted to character: a
The ASCII value 98 is converted to character: b
The ASCII value 99 is converted to character: c

在此程序中,foreach 循环遍历整数数组。数组中的每个整数都代表一个 ASCII 值。在循环中,整数值使用 (char) value 转换为 char。此转换操作将整数(假定为有效的 ASCII 或 Unicode 代码点)直接转换为相应的字符。然后将转换后的字符打印到控制台。

方法 3:使用模运算符

文件名:IntToCharModulo.java

输出

The number 1 is converted to character: A
The number 26 is converted to character: Z
The number 27 is converted to character: A
The number 52 is converted to character: Z
The number 53 is converted to character: A

方法 4:使用字符串数组和索引

文件名:IntToCharStringArray.java

输出

The number 1 is converted to character: A
The number 3 is converted to character: M
The number 5 is converted to character: P
The number 2 is converted to character: X
The number 4 is converted to character: K

Java int 转 char 选择题

1. 字符 'A' 的 Unicode 代码点是什么?

  1. 65
  2. 66
  3. 97
  4. 98

答案:A

解释:字符 'A' 的 Unicode 代码点是 65。


2. 以下哪个表达式可以在 Java 中正确地将 int 变量 num 转换为 char?

  1. (char) num
  2. Character.parseChar(num)
  3. num.toChar()
  4. Char.valueOf(num)

答案:A

解释:在 Java 中,使用 (char) 将 int 转换为 char 是正确的方法。


3. 以下代码的结果是什么?

  1. ch 将是 'A'。
  2. ch 将是 65。
  3. ch 将是 'B'。
  4. 编译错误。

答案:A

解释:整数值 65 在 Unicode 中对应于字符 'A',因此转换后,ch 将是 'A'。


4. 在 Java 中,可以使用哪种方法将 int 转换为 char,同时保留其 Unicode 值?

  1. (char) num
  2. Character.getCharValue(num)
  3. Char.valueOf(num)
  4. num.toChar()

答案:A

解释:在 Java 中,使用 (char) 将 int 转换为 char 可以保留其 Unicode 值。


5. 以下代码的结果是什么?

  1. ch 将是 'a'。
  2. ch 将是 'b'。
  3. ch 将是 '97'。
  4. 编译错误。

答案:B

解释:将整数值 97 加 1 得到 98,在 Unicode 中对应字符 'b',因此转换后,ch 将是 'b'。