Menu
Topics Index
...
`

Get from List


If you need explanation Read this topic

If you need Answer Take test on this topic

Get from List
What will be the output of the following program?
import java.util.*;
public class PrintList {
    public static void main(String args[]) {
        int i = 132;
        List list = new ArrayList();
        list.add(new Object());
        list.add("Hey! How are you?");
        list.add(i);
        System.out.println(list.get(1));
    }
}

A. 132
B. Hey! How are you?
C. Some other output
D. Compilation Error or Runtime Error
Topic: Java ArrayList

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

b. is right
list.add will print whole string

Posted by Shubham Bansal    2014-10-17 09:30:42


Ans is B
Here we are dealing with List interface and ArrayList class

ArrayList is an class which implements List interface
Array list can store the hetrogenious elements and even "null" can be stored

here in this program we create an array list with default size 10
here we are adding different type of elements Object,String,Integer

ArrayList stores everything interms of the Objects only..here int wil convert as Integer by using the autoboxing concept
by using get(1) we are accesing the 2nd Object which is String..
ArrayList indexes starts from the 0

Posted by Uday Kumar    2014-10-17 15:04:49


ans b.

ArrayList class extends AbstractList and implements the List interface.

ArrayList is a generic class
class ArrayList<E>
E specifies object type.

ArrayList support dynamic arrays that can grow as needed.

using add method we can add any number of objects of any type.

in this program 3 objects of different types get added.so size of list 3

we can use get() method to retrieve object from arraylist.
here 0 th indx new object (),
1st index string object
2 nd index integer object -int wrapper.
so primitive acts as object.

get(1) retrieve "hey! how are you?" string object.
sop printed

Posted by Maheshwari Natarajan    2014-10-17 17:50:35


This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Šâí Râm for the 'Popular Comment'. The 'lucky liker' is Šâí Râm. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-10-20 13:01:28


© meritcampus 2019

All Rights Reserved.

Open In App