如下代码:
public class Test{
    private String str="我们"。
}将Test编译之后形成class文件,那么在class文件中"我们"会以一种CONSTANT_UTF8_info表的形式存在,字节序列如下:
1 0 6 230 136 145 228 187 172    1表示常量表的类型,0 6表示有6个字节的长度。后面6个字节是UTF-8编码的“我们”。当JVM运行的时候会将这些常量池的信息加载进方法区。也就是说在运行过程中内存存储的"我们"是UTF-8编码的。我想问一下在Java程序运行时,内存中的字符到底是UTF-16编码的Unicode码,还是UTF-8编码的Unicode码。

解决方案 »

  1.   

    弄个winhex 去看下字节码文件里和内存里有什么不同
      

  2.   

    好题
    运行时是什么概念?你是说字节码存储和运行时的形态会不一致?
    运行时将字节码解释为本地系统码执行,我觉得可以不用再转也能满足运行的要求
    我想既然字节码已经能够以UTF-8编码存储了,楼主为什么还会想到UTF-16呢
      

  3.   

    好题
    肯定是UTF-8编码的了 
    一个个字符拼凑起来就成了一个串了
      

  4.   


    虽然知道Java中的字符时Unicode码,但是并不清楚在内存中存储的编码方式。说来惭愧,以前一直以为是UTF-16的编码方式,因为仅仅是自己对这种编码很熟悉而已。最近一直在研究JVM规范和运行机制,才开始感觉自己原来很多想当然的想法是错误的。不过,虽然我知道字节码确实UTF-8的字节序列,但是在谁还是能证实一下运行过程中内存中确实是UTF-8的编码形式,千万不要告诉我str.getByte();就OK了???
      

  5.   

    在java中,class文件采用utf8的编码方式,JVM运行时采用utf16。
      

  6.   

    未必错误哦,现在找了些资料,零零碎碎地印证了UTF-16Java originally used UCS-2, and added UTF-16 supplementary character support in J2SE 5.0. 
    Java uses UTF-16 as internal format for all strings
    http://en.wikipedia.org/wiki/UTF-16/UCS-2
      

  7.   

    另一表述:
    UTF-8 is most common on the web. UTF-16 is used by Java and Windows. UTF-32 is used by various Unix systems. The conversions between all of them are algorithmically based, fast and lossless. This makes it easy to support data input or output in multiple formats, while using a particular UTF for internal storage or processing.原因的话从UTF-8与UTF-16比较的劣势中去找:
    Disadvantages
        * A simplistic parser for UTF-16 is unlikely[citation needed] to convert invalid sequences to ASCII. Since the dangerous characters in most situations are ASCII, a simplistic UTF-16 parser is much less dangerous than a simplistic UTF-8 parser.
        * Characters U+0800 through U+FFFF use three bytes in UTF-8, but only two in UTF-16. As a result, text in (for example) Chinese, Japanese or Hindi could take more space in UTF-8 if there are more of these characters than there are ASCII characters. This rarely happens in real documents, for example both the Japanese and the Korean UTF-8 article on Wikipedia take more space if saved as UTF-16 than the original UTF-8 version [22]
        * In UCS-2 (but not UTF-16) Unicode code points are all the same size, making measurements of a fixed number of them easy. Due to ASCII-era documentation where "character" is used as a synonym for "byte" this is often considered important. Most UTF-16 implementations, including Windows, measure UTF-16 non-BMP characters as 2 units, as this is the only practical way to handle the strings. The same applies to UTF-8.安全,空间和易数,我想更多是前两者吧