Reputation: 2931
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
Reputation: 10524
Yes, it certainly will.
Here are some API descriptions of how println(Object)
and print(Object)
methods work.
Upvotes: 1
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