Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between printing char and int arrays in Java [duplicate]

Tags:

java

arrays

When I run the following code I get the address of the array:

int arr[] = {2,5,3};
System.out.println(arr); // [I@3fe993

But when I declare a character array and print it the same way it gives me the actual content of the array. Why?

char ch[] = {'a','b','c'};
System.out.println(ch); // abc
like image 576
Shashank Agarwal Avatar asked Jul 18 '14 19:07

Shashank Agarwal


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. Parameters: This method accepts a mandatory parameter charArray which is the character array to be printed in the Stream.

Which function is used to copy elements of an array in two variables?

Copying Arrays Using copyOfRange() method int[] destination1 = Arrays. copyOfRange(source, 0, source. length);

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.


1 Answers

Class PrintStream (which is what System.out is) has a dedicated method overload println(char[]) which prints the characters of a char array.

It has no special overloads for other arrays, so when you pass an int[] the called method is println(Object). That method converts the passed object to a string by calling its toString() method.

The toString() method for all arrays is simply the default one inherited from class Object, which displays their class name and default hashcode, which is why it's not so informative. You can use Arrays.toString(int[]) to get a string representation of your int array's contents.

P.S. Contrary to what the doc says, the default hashcode of an object is not typically the object's address, but a randomly generated number.

like image 78
Boann Avatar answered Oct 11 '22 12:10

Boann