人生需要总结

为什么Java中一个char能存下一个汉字

在Java中,char的长度是2字节,即16位,2的16次方是65536。

1、如果采用utf-8编码,一个汉字占3个字节,char为什么还能存下一个汉字呢?

参考:https://developer.aliyun.com/ask/65417?spm=a2c6h.13159736、https://blog.csdn.net/shipfei_csdn/article/details/81900952、https://blog.csdn.net/Sugar_Z_/article/details/51276984

因为Java使用Unicode字符集,Unicode用两个字节表示世界上所有的文字集合。utf-8是字符编码。字符集和字符编码不一样。

一个java文件使用utf-8编码,经过编译之后,使用unicode字符集。

字符集,就是包含各种字符的集合。utf-8是用来给unicode进行编码的。

utf-8字符编码,就是把字符和字节对应起来的一种方式。

2、遇到生僻字,String是咋存的?

示例代码:

public static void charTest() {
        String s = "𥔲";
        System.out.println(s + ",length:" + s.length());
        for(int i=0; i<s.length(); i++) {
            int num = s.charAt(i);
            System.out.println(s.charAt(i) + "---" + num);
        }
    }

打印结果:

𥔲,length:2
?---55381
?---56626

证明:char只能存储特定范围内的汉字,超过了还是存不下。

 

posted @ 2019-09-09 22:32  水木桶  阅读(1945)  评论(1编辑  收藏  举报