Code Snippets-based MCQs

Lists & Sets

Table of contents
  1. Easy Level MCQs
  2. Slightly harder MCQs
  3. Tricky MCQs

Easy Level MCQs

  1. What will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<String> list = new ArrayList<>();
             list.add("A");
             list.add("B");
             list.add("C");
             System.out.println(list.size());
         }
     }
    
    0
    2
    3
    Compilation error
    Answer

    3

  2. What will the following code snippet print?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Integer> set = new HashSet<>();
             set.add(1);
             set.add(2);
             set.add(1);
             System.out.println(set.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    2

  3. What will be the output of the following code snippet?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<String> list = new LinkedList<>();
             list.add("A");
             list.add("B");
             list.remove(1);
             System.out.println(list);
         }
     }
    
    [A, B]
    [B]
    [A]
    Compilation error
    Answer

    [A]

  4. What will the following code snippet print?

     import java.util.LinkedHashSet;
     public class Example {
         public static void main(String[] args) {
             LinkedHashSet<String> set = new LinkedHashSet<>();
             set.add("A");
             set.add("B");
             set.add("C");
             for (String s : set) {
                 System.out.print(s + " ");
             }
         }
     }
    
    C B A
    A C B
    B A C
    A B C
    Answer

    A B C

  5. What will be the output of the following code snippet?

     import java.util.Vector;
     public class Example {
         public static void main(String[] args) {
             Vector<Integer> vector = new Vector<>(2);
             vector.add(1);
             vector.add(2);
             vector.add(3);
             System.out.println(vector.size());
         }
     }
    
    2
    3
    4
    Compilation error
    Answer

    3

  6. What will the following code snippet print?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Integer> list = new ArrayList<>();
             list.add(1);
             list.add(2);
             list.add(3);
             for (int num : list) {
                 System.out.print(num + " ");
             }
         }
     }
    
    1 2
    2 3
    1 2 3
    Compilation error
    Answer

    1 2 3

  7. What will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<String> set = new TreeSet<>();
             set.add("Banana");
             set.add("Apple");
             set.add("Mango");
             System.out.println(set.first());
         }
     }
    
    Apple
    Banana
    Mango
    Compilation error
    Answer

    Apple

  8. What will the following code snippet print?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<Integer> list = new LinkedList<>();
             list.add(10);
             list.add(20);
             list.addFirst(5);
             System.out.println(list.get(0));
         }
     }
    
    10
    5
    20
    Compilation error
    Answer

    5

  9. What will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<String> set = new HashSet<>();
             set.add("X");
             set.add("Y");
             set.add("Z");
             set.remove("Y");
             System.out.println(set.contains("Y"));
         }
     }
    
    true
    false
    Compilation error
    Exception
    Answer

    false

  10. What will the following code snippet print?

    import java.util.Vector;
    public class Example {
        public static void main(String[] args) {
            Vector<Integer> vector = new Vector<>();
            vector.add(1);
            vector.add(2);
            vector.set(1, 3);
            System.out.println(vector.get(1));
        }
    }
    
    1
    2
    3
    Compilation error
    Answer

    3

  11. What will happen when the following code snippet is executed?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<int> list = new ArrayList<>();
             list.add(1);
             list.add(2);
             System.out.println(list.size());
         }
     }
    
    Prints 2
    Prints 0
    Compilation error
    Runtime error
    Answer

    Compilation error

    Explanation: In Java, generic types cannot be primitive types like int. Instead, you should use the wrapper class Integer. The correct declaration would be ArrayList<Integer> list = new ArrayList<>();.

  12. What will be the output when the following code snippet is executed?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<String> set = new HashSet<>();
             set.add("A");
             set.add("B");
             set.add("C");
             for (int i = 0; i < set.size(); i++) {
                 System.out.print(set.get(i) + " ");
             }
         }
     }
    
    A B C
    C B A
    Compilation error
    Runtime error
    Answer

    Compilation error

    Explanation: The HashSet class does not have a get(int index) method. Sets in Java do not support indexed access because they are unordered collections. To iterate over a set, you should use an iterator or a for-each loop.

  13. What will happen when the following code snippet is executed?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<String> list = new LinkedList<>();
             list.add("Hello");
             list.add("World");
             list.add(2, "!");
             System.out.println(list);
         }
     }
    
    [Hello, World, !]
    [Hello, !, World]
    [!, Hello, World]
    Runtime error
    Answer

    [Hello, World, !]

    Explanation: The add(int index, E element) method inserts the specified element at the specified position. Since the list initially has two elements at indices 0 and 1, adding an element at index 2 appends it to the end. Therefore, the list becomes [Hello, World, !].

  14. What will be the result of executing the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Integer> set = new TreeSet<>();
             set.add(null);
             set.add(1);
             set.add(2);
             System.out.println(set);
         }
     }
    
    [null, 1, 2]
    [1, 2]
    Compilation error
    Runtime error
    Answer

    Runtime error

    Explanation: Adding null to a TreeSet will throw a NullPointerException at runtime because TreeSet requires elements to be comparable for sorting, and null cannot be compared.

  15. What will happen when the following code snippet is executed?

     import java.util.Vector;
     public class Example {
         public static void main(String[] args) {
             Vector<String> vector = new Vector<>(-1);
             vector.add("A");
             vector.add("B");
             System.out.println(vector.size());
         }
     }
    
    Prints 2
    Prints 0
    Compilation error
    Runtime error
    Answer

    Runtime error

    Explanation: Initializing a Vector with a negative initial capacity will throw an IllegalArgumentException at runtime.

  16. What will be the output when the following code snippet is executed?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<String> list = new ArrayList<>();
             list.add("One");
             list.add("Two");
             list.add("Three");
             for (String s : list) {
                 if (s.equals("Two")) {
                     list.remove(s);
                 }
             }
             System.out.println(list);
         }
     }
    
    [One, Three]
    [One, Two, Three]
    [One, Three, Two]
    Runtime error
    Answer

    Runtime error

    Explanation: Removing elements from a list while iterating over it using a for-each loop will throw a ConcurrentModificationException at runtime. To safely remove elements, use an iterator’s remove() method.

  17. What will happen when the following code snippet is executed?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Integer> set = new HashSet<>();
             set.add(1);
             set.add(2);
             set.add(3);
             for (Integer num : set) {
                 if (num == 2) {
                     set.add(4);
                 }
             }
             System.out.println(set.size());
         }
     }
    
    4
    3
    Compilation error
    Runtime error
    Answer

    Runtime error

    Explanation: Modifying a HashSet while iterating over it will throw a ConcurrentModificationException at runtime.

  18. What will be the output when the following code snippet is executed?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<String> list = new LinkedList<>();
             list.add("A");
             list.add("B");
             list.add("C");
             System.out.println(list.get(3));
         }
     }
    
    C
    null
    Compilation error
    Runtime error
    Answer

    Runtime error

    Explanation: The get(int index) method will throw an IndexOutOfBoundsException if the index is out of range. Since the list has elements at indices 0, 1, and 2, trying to access index 3 will cause a runtime error.

  19. What will happen when the following code snippet is executed?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<String> set = new TreeSet<>();
             set.add("Apple");
             set.add("apple");
             set.add("Banana");
             System.out.println(set);
         }
     }
    
    [Apple, Banana, apple]
    [Apple, apple, Banana]
    [Banana, Apple, apple]
    [Apple, Banana]
    Answer

    [Apple, Banana, apple]

    Explanation: TreeSet sorts elements according to their natural ordering. In Java, uppercase letters come before lowercase letters in Unicode, so “Apple” < “Banana” < “apple”. Therefore, the set will be ordered as [Apple, Banana, apple].

  20. What will be the output when the following code snippet is executed?

    import java.util.Vector;
    public class Example {
        public static void main(String[] args) {
            Vector vector = new Vector();
            vector.add("1");
            vector.add(2);
            for (Object obj : vector) {
                System.out.print((String) obj + " ");
            }
        }
    }
    
    1 2
    Compilation error
    Runtime error
    1
    Answer

    Runtime error

    Explanation: The code attempts to cast an Integer object (2) to a String, which will throw a ClassCastException at runtime. To avoid this, ensure that all elements are of the same type or handle casting appropriately.

Back to Top

Slightly harder MCQs

  1. What will be the output of the following code snippet?

     import java.util.HashSet;
     import java.util.Iterator;
     public class Example {
         public static void main(String[] args) {
             HashSet<Integer> set = new HashSet<>();
             set.add(10);
             set.add(20);
             set.add(30);
             Iterator<Integer> it = set.iterator();
             while (it.hasNext()) {
                 Integer value = it.next();
                 if (value % 20 == 0) {
                     it.remove();
                 }
             }
             System.out.println(set);
         }
     }
    
    [10, 30]
    [10, 20, 30]
    [10]
    []
    Answer

    [10, 30]

    Explanation: The code removes elements divisible by 20 using an iterator’s remove() method. Since 20 is divisible by 20, it is removed, leaving [10, 30] in the set.

  2. What will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Integer> list = new ArrayList<>();
             list.add(10);
             list.add(20);
             list.add(30);
             for (int i = 0; i < list.size(); i++) {
                 list.set(i, list.get(i) + 10);
             }
             System.out.println(list);
         }
     }
    
    [20, 30, 40]
    [10, 20, 30]
    [20, 40, 60]
    [30, 40, 50]
    Answer

    [20, 30, 40]

    Explanation: The code iterates through the list and increases each element by 10 using the set method. The final list is [20, 30, 40].

  3. What will happen when the following code snippet is executed?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<String> list = new LinkedList<>();
             list.add("A");
             list.add("B");
             list.add("C");
             list.removeFirst();
             list.addFirst("D");
             System.out.println(list);
         }
     }
    
    [D, A, B, C]
    [D, B, C]
    [A, B, C, D]
    [B, C, D]
    Answer

    [D, B, C]

    Explanation: The code first removes the first element “A” from the list, and then adds “D” to the beginning. The final list is [D, B, C].

  4. What will happen when the following code snippet is executed?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Integer> set = new TreeSet<>();
             set.add(10);
             set.add(5);
             set.add(20);
             set.add(5);
             System.out.println(set);
         }
     }
    
    [5, 10, 20]
    [5, 10, 20, 5]
    [10, 5, 20]
    [20, 10, 5]
    Answer

    [5, 10, 20]

    Explanation: TreeSet maintains a sorted order and does not allow duplicate elements. The final set is [5, 10, 20].

  5. What will be the result of executing the following code snippet?

     import java.util.Vector;
     public class Example {
         public static void main(String[] args) {
             Vector<String> vector = new Vector<>();
             vector.add("A");
             vector.add("B");
             vector.add("C");
             vector.add(1, "D");
             vector.remove("C");
             System.out.println(vector);
         }
     }
    
    [A, D, B]
    [A, B, D]
    [A, B]
    [D, A, B]
    Answer

    [A, D, B]

    Explanation: The code inserts “D” at index 1, shifting the elements to the right, and then removes “C”. The final vector is [A, D, B].

  6. What will be the output when the following code snippet is executed?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Integer> set = new HashSet<>();
             set.add(1);
             set.add(2);
             set.add(3);
             set.add(2);
             System.out.println(set.size());
         }
     }
    
    3
    4
    2
    1
    Answer

    3

    Explanation: HashSet does not allow duplicate elements, so adding “2” twice has no effect. The set contains 3 unique elements: 1, 2, and 3.

  7. What will happen when the following code snippet is executed?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<Integer> list = new LinkedList<>();
             list.add(1);
             list.add(2);
             list.add(3);
             list.addLast(4);
             list.removeFirst();
             System.out.println(list);
         }
     }
    
    [1, 2, 3, 4]
    [2, 3, 4]
    [3, 4]
    [4, 3, 2, 1]
    Answer

    [2, 3, 4]

    Explanation: The code adds 4 to the end of the list and then removes the first element, resulting in the list [2, 3, 4].

  8. What will happen when the following code snippet is executed?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<String> set = new TreeSet<>();
             set.add("Banana");
             set.add("Apple");
             set.add("Mango");
             System.out.println(set);
         }
     }
    
    [Banana, Apple, Mango]
    [Apple, Banana, Mango]
    [Mango, Apple, Banana]
    [Apple, Mango, Banana]
    Answer

    [Apple, Banana, Mango]

    Explanation: TreeSet stores elements in a natural sorted order. The final set is [Apple, Banana, Mango].

  9. What will be the output when the following code is executed?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Integer> list = new ArrayList<>();
             list.add(1);
             list.add(2);
             list.add(3);
             list.add(0, 0);
             list.remove(2);
             System.out.println(list);
         }
     }
    
    [0, 1, 2, 3]
    [0, 2, 3]
    [0, 1, 3]
    [1, 2, 3]
    Answer

    [0, 1, 3]

    Explanation: The code inserts 0 at the beginning of the list, and then removes the element at index 2 (which is 2), resulting in [0, 1, 3].

  10. What will be the output when the following code snippet is executed?

    import java.util.HashSet;
    public class Example {
        public static void main(String[] args) {
            HashSet<String> set = new HashSet<>();
            set.add("apple");
            set.add("banana");
            set.add("cherry");
            set.add("banana");
            System.out.println(set.contains("banana"));
        }
    }
    
    false
    true
    Compilation error
    Runtime error
    Answer

    true

    Explanation: HashSet allows only unique elements, and the contains method checks if an element exists in the set. Since “banana” is in the set, the output is true.

  11. Given a Student class with a constructor that initializes the name and age fields, what will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Student> students = new ArrayList<>();
             students.add(new Student("Alice", 20));
             students.add(new Student("Bob", 22));
             students.add(new Student("Charlie", 21));
             System.out.println(students.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    3

    Explanation: The code adds three Student objects to the ArrayList, so the size of the list is 3.

  12. Given a Student class with a name field and a method getName() that returns the student’s name, what will be the output of the following code snippet?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<Student> students = new LinkedList<>();
             students.add(new Student("Alice"));
             students.add(new Student("Bob"));
             students.addFirst(new Student("Eve"));
             System.out.println(students.getFirst().getName());
         }
     }
    
    Alice
    Bob
    Eve
    Compilation error
    Answer

    Eve

    Explanation: addFirst inserts the student “Eve” at the beginning of the list, so getFirst().getName() returns “Eve”.

  13. Given a Student class with fields name and age, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Student> students = new HashSet<>();
             students.add(new Student("Alice", 20));
             students.add(new Student("Bob", 22));
             students.add(new Student("Alice", 20));
             System.out.println(students.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    2

    Explanation: If the Student class does not override equals and hashCode, the two Student objects with the same data are treated as different objects. So, the size of the set is 2.

  14. Given a Student class with fields name and age, what will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Student> students = new TreeSet<>();
             students.add(new Student("Alice", 20));
             students.add(new Student("Bob", 22));
             students.add(new Student("Charlie", 21));
             System.out.println(students);
         }
     }
    
    [Alice, Bob, Charlie]
    [Charlie, Bob, Alice]
    [Bob, Alice, Charlie]
    Compilation error
    Answer

    Compilation error

    Explanation: TreeSet requires elements to be comparable, so the Student class must implement Comparable or provide a Comparator when creating the TreeSet.

  15. Given a Student class with fields name and age, what will be the output of the following code snippet?

     import java.util.Vector;
     public class Example {
         public static void main(String[] args) {
             Vector<Student> students = new Vector<>();
             students.add(new Student("Alice", 20));
             students.add(new Student("Bob", 22));
             students.add(new Student("Charlie", 21));
             students.remove(1);
             System.out.println(students.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    2

    Explanation: The code removes the student at index 1, so the size of the Vector becomes 2.

  16. Given a Student class with fields name and grade, what will be the output of the following code snippet?

     import java.util.LinkedHashSet;
     public class Example {
         public static void main(String[] args) {
             LinkedHashSet<Student> students = new LinkedHashSet<>();
             students.add(new Student("Alice", "A"));
             students.add(new Student("Bob", "B"));
             students.add(new Student("Charlie", "C"));
             for (Student student : students) {
                 System.out.print(student.getName() + " ");
             }
         }
     }
    
    Alice Bob Charlie
    Charlie Bob Alice
    Bob Charlie Alice
    Compilation error
    Answer

    Alice Bob Charlie

    Explanation: LinkedHashSet maintains the insertion order, so the elements are printed in the order they were added.

  17. Given a Student class with fields name and grade, what will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Student> students = new ArrayList<>();
             students.add(new Student("Alice", "A"));
             students.add(new Student("Bob", "B"));
             students.add(new Student("Charlie", "C"));
             students.clear();
             System.out.println(students.isEmpty());
         }
     }
    
    true
    false
    Compilation error
    Runtime error
    Answer

    true

    Explanation: The clear() method removes all elements from the list, making it empty. The isEmpty() method returns true.

  18. Given a Student class with fields name and marks, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Student> students = new HashSet<>();
             students.add(new Student("Alice", 85));
             students.add(new Student("Bob", 92));
             students.add(new Student("Charlie", 78));
             for (Student student : students) {
                 if (student.getMarks() > 80) {
                     System.out.print(student.getName() + " ");
                 }
             }
         }
     }
    
    Alice Bob
    Bob
    Alice Charlie
    Bob Alice Charlie
    Answer

    Alice Bob

    Explanation: The code prints the names of students with marks greater than 80, so “Alice” and “Bob” are printed.

  19. Given a Student class with fields name and marks, what will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() {
                 public int compare(Student s1, Student s2) {
                     return s2.getMarks() - s1.getMarks();
                 }
             });
             students.add(new Student("Alice", 85));
             students.add(new Student("Bob", 92));
             students.add(new Student("Charlie", 78));
             System.out.println(students.first().getName());
         }
     }
    
    Alice
    Bob
    Charlie
    Compilation error
    Answer

    Bob

    Explanation: The custom comparator sorts students by marks in descending order, so first() returns “Bob”, who has the highest marks.

  20. Given a Student class with fields name and marks, what will be the output of the following code snippet?

    import java.util.Vector;
    public class Example {
        public static void main(String[] args) {
            Vector<Student> students = new Vector<>();
            students.add(new Student("Alice", 85));
            students.add(new Student("Bob", 92));
            students.add(new Student("Charlie", 78));
            students.remove(new Student("Alice", 85));
            System.out.println(students.size());
        }
    }
    
    1
    2
    3
    Compilation error
    Answer

    2

    Explanation: If the Student class does not override equals and hashCode, the remove method won’t find a match, and the size remains unchanged at 3. If it does, the size will be 2.

  21. Given a Book class with fields title and author, what will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Book> books = new ArrayList<>();
             books.add(new Book("1984", "George Orwell"));
             books.add(new Book("Brave New World", "Aldous Huxley"));
             books.add(new Book("Fahrenheit 451", "Ray Bradbury"));
             System.out.println(books.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    3

    Explanation: The code adds three Book objects to the ArrayList, so the size of the list is 3.

  22. Given a Movie class with fields title and year, what will be the output of the following code snippet?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<Movie> movies = new LinkedList<>();
             movies.add(new Movie("Inception", 2010));
             movies.add(new Movie("The Matrix", 1999));
             movies.addFirst(new Movie("Interstellar", 2014));
             System.out.println(movies.getFirst().getTitle());
         }
     }
    
    Inception
    The Matrix
    Interstellar
    Compilation error
    Answer

    Interstellar

    Explanation: addFirst inserts the movie “Interstellar” at the beginning of the list, so getFirst().getTitle() returns “Interstellar”.

  23. Given a Person class with fields name and age, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Person> people = new HashSet<>();
             people.add(new Person("Alice", 30));
             people.add(new Person("Bob", 25));
             people.add(new Person("Alice", 30));
             System.out.println(people.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    2

    Explanation: If the Person class does not override equals and hashCode, the two Person objects with the same data are treated as different objects. So, the size of the set is 2.

  24. Given a Song class with fields title and artist, what will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Song> playlist = new TreeSet<>();
             playlist.add(new Song("Bohemian Rhapsody", "Queen"));
             playlist.add(new Song("Stairway to Heaven", "Led Zeppelin"));
             playlist.add(new Song("Hotel California", "Eagles"));
             System.out.println(playlist);
         }
     }
    
    [Bohemian Rhapsody, Stairway to Heaven, Hotel California]
    [Stairway to Heaven, Bohemian Rhapsody, Hotel California]
    [Hotel California, Stairway to Heaven, Bohemian Rhapsody]
    Compilation error
    Answer

    Compilation error

    Explanation: TreeSet requires elements to be comparable, so the Song class must implement Comparable or provide a Comparator when creating the TreeSet.

  25. Given a Product class with fields name and price, what will be the output of the following code snippet?

     import java.util.Vector;
     public class Example {
         public static void main(String[] args) {
             Vector<Product> products = new Vector<>();
             products.add(new Product("Laptop", 1000));
             products.add(new Product("Smartphone", 700));
             products.add(new Product("Tablet", 500));
             products.remove(1);
             System.out.println(products.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    2

    Explanation: The code removes the product at index 1, so the size of the Vector becomes 2.

  26. Given a City class with fields name and population, what will be the output of the following code snippet?

     import java.util.LinkedHashSet;
     public class Example {
         public static void main(String[] args) {
             LinkedHashSet<City> cities = new LinkedHashSet<>();
             cities.add(new City("New York", 8419000));
             cities.add(new City("Los Angeles", 3980000));
             cities.add(new City("Chicago", 2716000));
             for (City city : cities) {
                 System.out.print(city.getName() + " ");
             }
         }
     }
    
    New York Los Angeles Chicago
    Chicago Los Angeles New York
    Los Angeles Chicago New York
    Compilation error
    Answer

    New York Los Angeles Chicago

    Explanation: LinkedHashSet maintains the insertion order, so the elements are printed in the order they were added.

  27. Given an Animal class with fields species and age, what will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Animal> zoo = new ArrayList<>();
             zoo.add(new Animal("Elephant", 10));
             zoo.add(new Animal("Tiger", 5));
             zoo.add(new Animal("Giraffe", 7));
             zoo.clear();
             System.out.println(zoo.isEmpty());
         }
     }
    
    true
    false
    Compilation error
    Runtime error
    Answer

    true

    Explanation: The clear() method removes all elements from the list, making it empty. The isEmpty() method returns true.

  28. Given a Car class with fields make and year, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Car> garage = new HashSet<>();
             garage.add(new Car("Toyota", 2018));
             garage.add(new Car("Honda", 2020));
             garage.add(new Car("Ford", 2019));
             for (Car car : garage) {
                 if (car.getYear() > 2018) {
                     System.out.print(car.getMake() + " ");
                 }
             }
         }
     }
    
    Toyota Honda Ford
    Honda Ford
    Ford Toyota
    Compilation error
    Answer

    Honda Ford

    Explanation: The loop checks if the car’s year is greater than 2018, so “Honda” and “Ford” are printed since they were manufactured after 2018.

  29. Given a Gadget class with fields name and price, what will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Gadget> gadgets = new TreeSet<>(new Comparator<Gadget>() {
                 public int compare(Gadget g1, Gadget g2) {
                     return g1.getPrice() - g2.getPrice();
                 }
             });
             gadgets.add(new Gadget("Smartphone", 700));
             gadgets.add(new Gadget("Tablet", 500));
             gadgets.add(new Gadget("Laptop", 1000));
             System.out.println(gadgets.last().getName());
         }
     }
    
    Smartphone
    Tablet
    Laptop
    Compilation error
    Answer

    Laptop

    Explanation: The custom comparator sorts the gadgets by price in ascending order, so the last element (highest price) is “Laptop”.

  30. Given a Course class with fields courseName and duration, what will be the output of the following code snippet?

    import java.util.LinkedList;
    public class Example {
        public static void main(String[] args) {
            LinkedList<Course> courses = new LinkedList<>();
            courses.add(new Course("Java", 30));
            courses.add(new Course("Python", 25));
            courses.add(new Course("JavaScript", 20));
            courses.removeLast();
            System.out.println(courses.getLast().getCourseName());
        }
    }
    
    Java
    Python
    JavaScript
    Compilation error
    Answer

    Python

    Explanation: The removeLast() method removes the last course in the list, leaving “Java” and “Python”. The getLast() method then returns the course name of the last remaining course, “Python”.

Back to Top

Tricky MCQs

  1. Given a Developer class with fields name and experience, and assuming equals and hashCode are correctly overridden, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Developer> team = new HashSet<>();
             Developer dev1 = new Developer("Alice", 5);
             Developer dev2 = new Developer("Bob", 3);
             team.add(dev1);
             team.add(dev2);
             dev1.setExperience(6);
             System.out.println(team.contains(new Developer("Alice", 6)));
         }
     }
    
    true
    false
    Compilation error
    Runtime error
    Answer

    false

    Explanation: Modifying an object in a HashSet after it’s been added can lead to unexpected behavior, as the object’s hash code might change, making it difficult to find the object.

  2. Given an Employee class with fields id and department, and assuming equals and hashCode are correctly overridden, what will be the output of the following code snippet?

     import java.util.LinkedHashSet;
     public class Example {
         public static void main(String[] args) {
             LinkedHashSet<Employee> employees = new LinkedHashSet<>();
             employees.add(new Employee(1, "HR"));
             employees.add(new Employee(2, "Finance"));
             employees.add(new Employee(1, "HR"));
             employees.add(new Employee(3, "Engineering"));
             System.out.println(employees.size());
         }
     }
    
    2
    3
    4
    Compilation error
    Answer

    3

    Explanation: Since equals and hashCode are overridden, duplicates based on the same id and department are not added. So the size is 3.

  3. Given a Course class with fields title and duration, and assuming Course implements Comparable<Course> based on title, what will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Course> courses = new TreeSet<>();
             courses.add(new Course("Math", 40));
             courses.add(new Course("Science", 35));
             courses.add(new Course("Math", 30));
             System.out.println(courses.size());
         }
     }
    
    1
    2
    3
    Compilation error
    Answer

    2

    Explanation: Since Course objects are compared based on title, “Math” is considered a duplicate, and only two unique courses (“Math” and “Science”) are added.

  4. Given a Building class with fields name and height, what will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Building> buildings = new ArrayList<>();
             buildings.add(new Building("Empire State", 1250));
             buildings.add(new Building("Burj Khalifa", 2717));
             buildings.remove(new Building("Empire State", 1250));
             System.out.println(buildings.size());
         }
     }
    
    1
    2
    0
    Compilation error
    Answer

    2

    Explanation: Without overriding equals and hashCode, remove does not find the object in the list, so the size remains 2.

  5. Given a Gadget class with fields model and price, and assuming equals and hashCode are correctly overridden, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Gadget> gadgets = new HashSet<>();
             gadgets.add(new Gadget("iPhone", 999));
             gadgets.add(new Gadget("iPhone", 999));
             gadgets.add(new Gadget("Samsung", 899));
             gadgets.add(new Gadget("iPhone", 1099));
             System.out.println(gadgets.size());
         }
     }
    
    2
    3
    4
    Compilation error
    Answer

    3

    Explanation: The first two “iPhone” gadgets are considered duplicates and are not added again, but the third “iPhone” with a different price is added.

  6. Given a Team class with fields name and rank, what will be the output of the following code snippet?

     import java.util.LinkedList;
     public class Example {
         public static void main(String[] args) {
             LinkedList<Team> teams = new LinkedList<>();
             teams.add(new Team("Alpha", 1));
             teams.add(new Team("Beta", 2));
             teams.add(new Team("Gamma", 3));
             teams.add(1, new Team("Delta", 4));
             System.out.println(teams.get(1).getName());
         }
     }
    
    Alpha
    Beta
    Delta
    Gamma
    Answer

    Delta

    Explanation: The add(1, new Team("Delta", 4)) inserts “Delta” at index 1, pushing the other elements to the right.

  7. Given a Library class with fields name and booksCount, and assuming Library implements Comparable<Library> based on booksCount, what will be the output of the following code snippet?

     import java.util.TreeSet;
     public class Example {
         public static void main(String[] args) {
             TreeSet<Library> libraries = new TreeSet<>();
             libraries.add(new Library("Central", 10000));
             libraries.add(new Library("East", 8000));
             libraries.add(new Library("West", 12000));
             libraries.add(new Library("Central", 10000));
             System.out.println(libraries.first().getName());
         }
     }
    
    Central
    East
    West
    Compilation error
    Answer

    East

    Explanation: The TreeSet orders libraries by booksCount, and the one with the smallest booksCount is “East”.

  8. Given a Student class with fields name and grade, and assuming equals and hashCode are correctly overridden, what will be the output of the following code snippet?

     import java.util.HashSet;
     public class Example {
         public static void main(String[] args) {
             HashSet<Student> students = new HashSet<>();
             Student s1 = new Student
    
     ("John", "A");
             Student s2 = new Student("Jane", "B");
             students.add(s1);
             students.add(s2);
             s1.setGrade("B");
             System.out.println(students.contains(new Student("John", "B")));
         }
     }
    
    true
    false
    Compilation error
    Runtime error
    Answer

    false

    Explanation: Changing s1’s grade after adding it to the set affects its hash code, making it difficult to find in the set, so contains returns false.

  9. Given a Country class with fields name and population, and assuming equals and hashCode are correctly overridden, what will be the output of the following code snippet?

     import java.util.ArrayList;
     public class Example {
         public static void main(String[] args) {
             ArrayList<Country> countries = new ArrayList<>();
             countries.add(new Country("USA", 331000000));
             countries.add(new Country("India", 1391000000));
             countries.add(new Country("China", 1440000000));
             countries.add(1, new Country("Russia", 146000000));
             countries.remove(0);
             System.out.println(countries.get(1).getName());
         }
     }
    
    Russia
    India
    China
    USA
    Answer

    India

    Explanation: “Russia” is added at index 1, pushing “India” to index 2. Removing index 0 removes “USA”, so “India” moves back to index 1.

  10. Given a Product class with fields name and price, and assuming Product implements Comparable<Product> based on price, what will be the output of the following code snippet?

    import java.util.TreeSet;
    public class Example {
        public static void main(String[] args) {
            TreeSet<Product> products = new TreeSet<>();
            products.add(new Product("Phone", 700));
            products.add(new Product("Tablet", 500));
            products.add(new Product("Laptop", 1200));
            System.out.println(products.pollFirst().getName());
        }
    }
    
    Phone
    Tablet
    Laptop
    Compilation error
    Answer

    Tablet

    Explanation: The TreeSet orders products by price, and pollFirst() retrieves and removes the lowest-priced product, which is “Tablet”.