Java: println with char array gives gibberish

时光总嘲笑我的痴心妄想 提交于 2019-11-28 09:39:36

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.

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

This is just like

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

You can look up "Object.toString()"

Use

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

The gibrish you get is the Class name followed by the memory address of the object. Problem occurs when you try to append b with a string char[] b: in this case the char array b.toString() method is called thus [C@56e5b723 is printed.

[ indicates that it is an array C indicates the class in this case char @56e5b723 indicates the memory location

An array's toString() method (which is what's called when you do "..." + b) is only meant to give debugging output. There isn't a special case where a char[]'s toString() will give you the original string - arrays of all types have the same toString() implementation.

If you want to get the original string from the char array, use:

String a2 = new String(b);

Use 3:e row!

Scanner input = new Scanner(System.in);
char[] txt = input.next().toCharArray();
System.out.println((char[])txt);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!