Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: println with char array gives gibberish

Here's the problem. This code:

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

returns

 0000 0000 


But this code:

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

returns

 String a: 0000 char[] b: [C@56e5b723 


What in the world is going on? Seems there should be a simple enough solution, but I can't seem to figure it out.

like image 486
stephenwade Avatar asked Nov 22 '12 02:11

stephenwade


People also ask

Can you print a char array in Java?

The println(char[]) method of PrintStream Class in Java is used to print the specified character array on the stream and then break the line. This character array is taken as a parameter.

How do I concatenate a char array to a string in Java?

Use the valueOf() method in Java to copy char array to string. You can also use the copyValueOf() method, which represents the character sequence in the array specified. Here, you can specify the part of array to be copied.

Can a char array hold string?

You can store a string in a char array of length 1, but it has to be empty: char a[1] = ""; The terminating null character is the only thing that can be stored.

Is char array better than string?

Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his elements as blank or zero. So Storing the password in a character array clearly mitigates security risk of stealing passwords.


1 Answers

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.

like image 102
Doug Moscrop Avatar answered Sep 28 '22 11:09

Doug Moscrop