Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Example99
{
    public static void main(String[] args)
    {
        List<Object> l = new ArrayList<Object>();
        l.add(l);
        System.out.println(l.size());
    }
}

  • A.Compilation fails.
  • B.The program prints 0
  • C.The program prints 1
  • D.A StackOverflowError is thrown.

Answer: C

A list may hold a reference to itself, so the add succeeds and the size is 1. Nothing recurses until something walks the structure: printing the list rather than its size would call toString on itself and the javadoc leaves that behaviour undefined.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.