Java quiz 17: Working with ArrayLists

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes    Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 

ArrayList is used in Java to collect data. If you are not familiar with ArrayLists, you can read this article about ArrayList.

Java quiz 17: Working with ArrayLists

Level: Hard

What is written to the standard output as the result of executing the following code?

import java.util.ArrayList;
import java.util.List;

public class MyList
  List<String> list = new ArrayList<String>();
  List<String> list2 = new ArrayList<String>();
  public List<String> method(List<String> list)
    return list;
  public static void main(String[] args)
    MyList ml1 = new MyList();
    ml1.list2 = ml1.method(ml1.list);
Author: Sar Maroof

Select the correct answer.

Answer explanation

  1. The statement ml1.list2 = ml1.method(ml1.list); makes the object list2 a reference to the object list, and adds the letters a and b to the list2.
  2. The statement ml1.list.add(“c”); adds the letter “c” to the list.
  3. The statment ml1.list.add(“d”); adds the letter “d”.
    Since list and list2 are referring to the same object. The code writes [a, b, c, d] to the standard output.

The correct answer is: b.

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply