Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a char array is an Object in Java, why does printing it not display its hash code?

Tags:

Printing a char array does not display a hash code:

class IntChararrayTest{     public static void main(String[] args){         int intArray[] = {0,1,2};         char charArray[] = {'a','b','c'};         System.out.println(intArray);         System.out.println(charArray);     } } 

output :

[I@19e0bfd abc 

Why is the integer array printed as a hashcode and not the char array?

like image 958
user2186831 Avatar asked Jul 04 '15 08:07

user2186831


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.

Is char array an object in Java?

First of all, a char array is an Object in Java just like any other type of array.

What will print if we print object in Java?

When we print the object, we can see that the output looks different. This is because while printing the object, the toString() method of the object class is called. It formats the object in the default format.


2 Answers

First of all, a char array is an Object in Java just like any other type of array. It is just printed differently.

PrintStream (which is the type of the System.out instance) has a special version of println for character arrays - public void println(char x[]) - so it doesn't have to call toString for that array. It eventually calls public void write(char cbuf[], int off, int len), which writes the characters of the array to the output stream.

That's why calling println for a char[] behaves differently than calling it for other types of arrays. For other array types, the public void println(Object x) overload is chosen, which calls String.valueOf(x), which calls x.toString(), which returns something like [I@19e0bfd for int arrays.

like image 87
Eran Avatar answered Oct 20 '22 16:10

Eran


The int array is an array of integers where as the char array of printable characters. The printwriter has the capability to print character arrays as this is how it prints string anyway. The printwriter will therefore print them like a string, without calling the toString() method to convert it to a string. Converting an int array to a string returns a hash code, explaining why you get that output.

Take this for example:

int[] ints = new int[] { 1, 2, 3 }; char[] chars = new char[] { '1', '2', '3' } 

If you were to print both those sequences using the method you used, it would print the hash code of the int array followed by '123'.

like image 42
rodit Avatar answered Oct 20 '22 17:10

rodit