Java: println with char array gives gibberish

前端 未结 5 1984
悲哀的现实
悲哀的现实 2020-12-10 01:04

Here\'s the problem. This code:

String a = \"0000\";
 System.out.println(a);
char[] b = a.toCharArray();
 System.out.println(b);

returns

5条回答
  •  情书的邮戳
    2020-12-10 01:26

    When you say

    System.out.println(b);
    

    It results in a call to print(char[] s) then println()

    The JavaDoc for print(char[] s) says:

    Print an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

    So it performs a byte-by-byte print out.

    When you say

    System.out.println("char[] b: " + b);
    

    It results in a call to print(String), and so what you're actually doing is appending to a String an Object which invokes toString() on the Object -- this, as with all Object by default, and in the case of an Array, prints the value of the reference (the memory address).

    You could do:

    System.out.println("char[] b: " + new String(b));
    

    Note that this is "wrong" in the sense that you're not paying any mind to encoding and are using the system default. Learn about encoding sooner rather than later.

提交回复
热议问题