tgoop.com/topJavaQuizExplain/292
Last Update:
What will be the output of the code?
❌ A. Hello null
❌ B. null 123
✅ C. Hello 123
❌ D. Compilation error
❌ E. Runtime error
❌ F. None of the above
Explanation:
1. Generic Class:
• The Container class is a generic class with a type parameter T.
2. Instances of Generic Class:
• Container<String> stringContainer = new Container<>(); creates a Container for String items.
• Container<Integer> integerContainer = new Container<>(); creates a Container for Integer items.
3. Setting Items:
• stringContainer.setItem("Hello"); sets the item of the stringContainer to "Hello".
• integerContainer.setItem(123); sets the item of the integerContainer to 123.
4. List of Containers:
• List<Container<?>> containerList = new ArrayList<>(); creates a list that can hold Container objects of any type.
• containerList.add(stringContainer); adds the stringContainer to the list.
• containerList.add(integerContainer); adds the integerContainer to the list.
5. Printing Items:
• The for loop iterates through each Container in the containerList.
• System.out.println(container.getItem()); prints the item stored in each Container.
Since stringContainer holds "Hello" and integerContainer holds 123, the output will be: 'Hello 123'. Thus, the correct answer is C.
BY Explanations “Top Java Quiz Questions”
Share with your friend now:
tgoop.com/topJavaQuizExplain/292