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.
If I have an array of objects which have a toString method and I
Share
Yes, it will.
The advantage, in fact, of doing this over implicitly calling
.toString()is that nulls are handled without throwing an exception. Ifarray[i]isnull,then System.out.println(array[i])will printnullwhereSystem.out.println(array[i].toString())will throw aNullPointerException.This is because the
System.out.println(object)method callsSystem.out.print(object)which callsString.valueOf(object)which in turn callsobject.toString().