different behaviour of println() in java

java, println

Solution

`println()` is overloaded to print an array of characters as a string, which is why the 2nd print statement works correctly:

`public void println(char[] x)`

Prints an array of characters and then terminate the line. This method behaves as though it invokes `print(char[])` and then `println()`.

Parameters: `x` - an array of chars to print.

The 1st `println()` statement, on the other hand, concatenates the array's `toString()` with another string. Since arrays don't override `toString()`, they default to `Object`'s implementation, which is what you see.

Problem

``` //take the input from user text = br.readLine(); //convert to char array char ary[] = text.toCharArray(); System.out.println("initial string is:" + text.toCharArray()); System.out.println(text.toCharArray()); ``` Output: ``` initial string is:[C@5603f377 abcd ```

Original source