Core Java - Collections - Interview Questions and Answers

What happens when you compile and run the below program?

package com.javatutorial.quiz;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class Quiz38 {
 
    public static void main(String[] args) {
 
        List<Integer> list = new ArrayList<Integer>();
        
        Integer[] arr = {2,10,3};
        
        list = Arrays.asList(arr);
        
        list.set(0, 3);
        
        System.out.println(list);
        
        list.add(1);
        
        System.out.println(list);
    }
 
}

Output:

[3,10,3], followed by exception

 Arrays.asList() returns a fixed-size list backed by the specified array. Therefore, the arraylist can't grow.
So, when add() is called, an exception is thrown.