java 中 char 和 int 的互相转换直接基于 unicode 码位进行,char 是 16 位无符号整数,int 是 32 位有符号整数。将 char 转为 int 时,通过隐式或显式类型提升获取其对应的 unicode 值;将 int 转回 char 时,需强制转换为 char 以截取低 16 位并映射回字符。这种转换不涉及编码格式的字节序列变化,而是数值层面的直接对应。

char 转 int 的具体行为是什么
当把 char 赋值给 int 时,Java 会自动进行 widening primitive conversion(拓宽基本类型转换),保留字符的 Unicode 码位值。例如 'A' 的码位是 65,转为 int 后就是 65。如果涉及 BOM 或特殊符号,同样按其在 Unicode 表中的位置取值。以下代码演示了常见字符的转换结果:
public class CharToIntDemo {
public static void main(String[] args) {
char c1 = 'A';
char c2 = '0';
char c3 = '\u4E2D'; // 中
int i1 = c1;
int i2 = c2;
int i3 = c3;
System.out.println("'A' -> " + i1);
System.out.println("'0' -> " + i2);
System.out.println("'中' -> " + i3);
}
}运行上述代码,预期输出为:
'A' -> 65
'0' -> 48
'中' -> 20013

立即学习“Java免费学习笔记(深入)”;
int 转 char 时的截断规则是什么
将 int 转为 char 属于 narrowing primitive conversion(收窄基本类型转换),会丢弃高 16 位,仅保留低 16 位作为 Unicode 码位。若 int 值超出 char 范围(0-65535),则发生截断。例如 int 值 65 转 char 得到 'A',而 int 值 70000 转 char 会得到 (char)(70000 % 65536) = 4464,对应字符 ''(实际是 U+1170)。以下代码验证这一行为:
public class IntToCharDemo {
public static void main(String[] args) {
int i1 = 65;
int i2 = 70000;
char c1 = (char) i1;
char c2 = (char) i2;
System.out.println("65 -> '" + c1 + "'");
System.out.println("70000 -> '" + c2 + "' (U+" + Integer.toHexString(c2) + ")");
}
}运行上述代码,预期输出为:
65 -> 'A'
70000 -> '' (U+1170)

使用 Character.codePointAt() 处理代理对时如何正确转换
对于超出 BMP(Basic Multilingual Plane)的 Unicode 字符(如 emoji 或生僻汉字),它们由两个 char 组成的代理对表示。此时不能直接用 char 到 int 的简单转换,而应使用 Character.codePointAt(char[], int) 获取完整的码位。反之,从 int 码位还原为 char 序列时,需用 Character.toChars(int)。以下代码展示如何处理代理对:
public class CodePointDemo {
public static void main(String[] args) {
String str = "?"; // U+20BB7, 一个代理对字符
int codePoint = Character.codePointAt(str, 0);
char[] chars = Character.toChars(codePoint);
System.out.println("CodePoint: " + codePoint);
System.out.println("Chars length: " + chars.length);
System.out.println("First char: " + chars[0] + " (U+" + Integer.toHexString(chars[0]) + ")");
System.out.println("Second char: " + chars[1] + " (U+" + Integer.toHexString(chars[1]) + ")");
}
}运行上述代码,预期输出为:
CodePoint: 134151
Chars length: 2
First char: (U+d842)
Second char: (U+bb7)


















