What will be the output of the following Java program? [code] import java.util.*; class Arraylist { public static

What will be the output of the following Java program?
Code:
    import java.util.*;
    class Arraylist 
    {
        public static void main(String args[]) 
        {
            ArrayList obj = new ArrayList();
            obj.add("A");
            obj.add("B");
            obj.add("C");
            obj.add(1, "D");
            System.out.println(obj);
        }
    }
A. [A, B, C, D]
B. [A, D, B, C]
C. [A, D, C]
D. [A, B, C]
 
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:
Code:
$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].
 

Tìm kiếm

Back
Top