From compilation to runtime, how does Java String encoding really work

后端 未结 4 1660
深忆病人
深忆病人 2020-12-30 02:39

I recently realized that I don\'t fully understand Java\'s string encoding process.

Consider the following code:

public class Main
{
    public stati         


        
4条回答
  •  隐瞒了意图╮
    2020-12-30 03:13

    1. Source files can be in any encoding
    2. You need to tell the compiler the encoding of source files (e.g. javac -encoding...); otherwise, platform encoding is assumed
    3. In class file binaries, string literals are stored as (modified) UTF-8, but unless you work with bytecode, this doesn't matter (see JVM spec)
    4. Strings in Java are UTF-16, always (see Java language spec)
    5. The System.out PrintStream will transform your strings from UTF-16 to bytes in the system encoding prior to writing them to stdout

    Notes:

    • Blog post I wrote on Java encoding
    • Don't use -Dfile.encoding

提交回复
热议问题