mark
mark

Reputation: 2931

Java - Printing a class

If I have an array of objects which have a toString method and I print the array using a for loop (e.g.: simply array[i] to reach the objects and carry out System.out.println(array[i])) will the toString method be invoked automatically? It seems to be but I just want to check this is what is going on.

Upvotes: 1

Views: 78

Answers (2)

Jagger
Jagger

Reputation: 10524

Yes, it certainly will.

Here are some API descriptions of how println(Object) and print(Object) methods work.

println(Object)

print(Object)

Upvotes: 1

Erick Robertson
Erick Robertson

Reputation: 33068

Yes, it will.

The advantage, in fact, of doing this over implicitly calling .toString() is that nulls are handled without throwing an exception. If array[i] is null, then System.out.println(array[i]) will print null where System.out.println(array[i].toString()) will throw a NullPointerException.

This is because the System.out.println(object) method calls System.out.print(object) which calls String.valueOf(object) which in turn calls object.toString().

Upvotes: 5

Related Questions