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.
2 Answers
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().
Comments
Yes, it certainly will.
Here are some API descriptions of how println(Object) and print(Object) methods work.