13

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
Boann
  • 48,794
  • 16
  • 117
  • 146
Shashank Agarwal
  • 1,122
  • 1
  • 8
  • 24
  • 1
    They have different implementations of `.toString()` – Bob Dalgleish Jul 18 '14 at 19:18
  • Your link was right on the money. Sorry. – PM 77-1 Jul 18 '14 at 19:30
  • 3
    The answer seems to be: because `PrintStream` class has a method for `array of characters` and does not have for arrays of any other primitives. – PM 77-1 Jul 18 '14 at 19:32
  • 2
    And not to beat a dead horse for @BobDalgleish, but they _don't_ have different implementations. All arrays in Java have the same `toString`, which is just the `Object.toString`. – yshavit Jul 18 '14 at 19:39

2 Answers2

17

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.

Boann
  • 48,794
  • 16
  • 117
  • 146
0

When you say System.out.println(ch);

It results in a call to print(char[] s) then println()

The JavaDoc for println says:

Prints a character and then terminate the line. This method behaves as though it invokes print(char) and then println().

A integer variable is not char, so the print(int[] s) get the address of array.

Jimmysnn
  • 583
  • 4
  • 8
  • 30