首页 > 解决方案 > java中英文和汉字各占多少字节?

问题描述

import java.io.UnsupportedEncodingException;

public class TestChar {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String cnStr = "龙";
        String enStr = "a";
        byte[] cnBytes = cnStr.getBytes("UTF-8");
        byte[] enBytes = enStr.getBytes("UTF-8");

        System.out.println("bytes size of Chinese:" + cnBytes.length);
        System.out.println("bytes size of English:" + enBytes.length);

        //  in java, char takes two bytes, the question is: 
        char cnc = '龙'; // will '龙‘ take two or three bytes ?
        char enc = 'a'; // will 'a' take one or two bytes ?
    }
}

输出

   bytes size of Chinese:3

   bytes size of English:1

这里,My JVM 设置为 UTF-8,从输出中我们知道汉字“龙”占 3 个字节,英文字符“a”占 1 个字节。我的问题是:

在 Java 中,char 占用两个字节,这里,char cnc = '龙'; 字符编码 = 'a'; cnc 只需要两个字节而不是 3 个字节吗?'a' 需要两个字节而不是一个字节?

标签: javaencodingcharacter

解决方案


UTF-8是一种变长字符编码,其中字符占用 1 到 4 个字节。

Javachar是 16 位的。请参阅Java 语言规范中的3.1 Unicode以了解 Java 究竟如何处理 Unicode。


推荐阅读