1

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.

0

2 Answers 2

5

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().

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it certainly will.

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

println(Object)

print(Object)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.