Answer: b
Explanation: obj is an object of class ArrayList hence it is an dynamic array which can increase and decrease its size. obj.add(“X”) adds to the array element X and obj.add(1,”X”) adds element x at index position 1 in the list, Hence obj.add(1,”D”) stores D at index position 1 of obj and shifts the previous value stored at that position by 1.
Output:

$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].

8. What is the output of this program?

importjava.util.*;

class Output

{

publicstaticvoid main(String args[])

{

ArrayList obj =newArrayList();

obj.add("A");

obj.add(0, "B");

System.out.println(obj.size());

}

}

a) 0
b) 1
c) 2
d) Any Garbage ValueView Answer

Answer: c
Explanation: None.
Output:

$ javac Output.java
$ java Output
2

9. What is the output of this program?

importjava.util.*;

class Output

{

publicstaticvoid main(String args[])

{

ArrayList obj =newArrayList();

obj.add("A");

obj.ensureCapacity(3);

System.out.println(obj.size());

}

}

a) 1
b) 2
c) 3
d) 4View Answer

Answer: a
Explanation: Although obj.ensureCapacity(3); has manually increased the capacity of obj to 3 but the value is stored only at index 0, therefore obj.size() returns the total number of elements stored in the obj i:e 1, it has nothing to do with ensureCapacity().
Output:

$ javac Output.java
$ java Output
1

10. What is the output of this program?

class Output

{

publicstaticvoid main(String args[])

{

ArrayList obj =newArrayList();

obj.add("A");

obj.add("D");

obj.ensureCapacity(3);

obj.trimToSize();

System.out.println(obj.size());

}

}

a) 1
b) 2
c) 3
d) 4View Answer

Answer: b
Explanation: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.
Output: