そう、いつだって忘れがち。文字列はJava内部ではUTF-16で扱われていることを。
import java.io.UnsupportedEncodingException;
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
// *** charの値をそのままintで表現 ***
char a = 'あ';
System.out.printf("%d : %X\n", (int)a, (int)a);
// ↑12354 : 3042 と表示される(UTF-16の文字コード)
// *** StringからcharAtで取得した値をintで表現 ***
char b = "あ".charAt(0);
System.out.printf("%d : %X\n", (int)a, (int)a);
// ↑12354 : 3042 と表示される(UTF-16の文字コード)
// *** UTF-16のバイト配列を使って文字列作成 ***
byte[] bytes = "あ".getBytes();
String s = new String(bytes, 0, bytes.length, "UTF-16");
char c = s.charAt(0); // 1文字目を取得
System.out.printf("%d : %X\n", (int)c, (int)c);
// ↑33440 : 82A0 と表示される(Shift-JISの文字コード)
}
}