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
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.
Copying Arrays Using copyOfRange() method int[] destination1 = Arrays. copyOfRange(source, 0, source. length);
First of all, a char array is an Object in Java just like any other type of array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With