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
4
  • 1
    They have different implementations of .toString() Commented Jul 18, 2014 at 19:18
  • Your link was right on the money. Sorry. Commented Jul 18, 2014 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. Commented Jul 18, 2014 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. Commented Jul 18, 2014 at 19:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it is internally invoking String.valueOf()
@JigarJoshi Which on non-null objects such as this, calls toString().
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.