Ok, so you know how, if we want to output the elements of an array to the screen, we have to make a for loop right?
So I have the following code...

char array[] = new char [10];
array[0] = '1';
array[1] = '2';
.
.
.
.
array[9] = '10';

for (int i = 0; i < 10; i++)
{
    System.out.println (array[i]);
}

BUT. when I take out the for loop.. and instead... just put a println statement...
the code becomes like:

char array[] = new char [10];
array[0] = '1';
array[1] = '2';
.
.
.
.
array[9] = '10';

System.out.println (array);

.. AND IT PRINTS OUT THE WHOLE ARRAY! :/

I am just confused... Why does that happen?
and it's only for char! when I tried for int, String or double, it just gave me gibberish (prolly just a memory address)...

please... please.. I am begging you :( Tell me why it does that :( I asked my teacher and even he doesn't know...

prolly just a memory address

That'll be right. An array is an object. If you feed an object as the argument to a print or println, it'll generally try to print it by calling String.valueOf(the object). That behavior is defined in the API, under String:

valueOf

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters:
obj - an Object.
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So, in general, it's going to call the object's toString(). Arrays don't override the toString method, so the default is called, the one defined in Object. Object's toString() returns the memory location, so that's what you get.

In the case of a char array, there's special behavior, because, as pinsickle observes, the method is overloaded.

I go through this whole story so you can see that there are two ways in which the behavior of print(someObject) can vary. One is if someObject is of a type that overloads toString - then it'll print whatever toString returns. The other is if the String class happens to overload the method for someObject's class, in which case you might get some behavior that the author of the String class thought would be useful.

You also might find it useful to study this stuff up and go back and explain it to your teacher. If you can explain this in your own words, you'll have a solid grasp of some important ideas in java.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.