Code Snippets-based MCQs
Lists & Sets
Table of contents
Easy Level MCQs
-
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()); } }
Answer
3
-
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()); } }
Answer
2
-
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); } }
Answer
[A]
-
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 + " "); } } }
Answer
A B C
-
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()); } }
Answer
3
-
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 + " "); } } }
Answer
1 2 3
-
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()); } }
Answer
Apple
-
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)); } }
Answer
5
-
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")); } }
Answer
false
-
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)); } }
Answer
3
-
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()); } }
Answer
Compilation error
Explanation: In Java, generic types cannot be primitive types like
int
. Instead, you should use the wrapper classInteger
. The correct declaration would beArrayList<Integer> list = new ArrayList<>();
. -
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) + " "); } } }
Answer
Compilation error
Explanation: The
HashSet
class does not have aget(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. -
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); } }
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, !]
. -
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); } }
Answer
Runtime error
Explanation: Adding
null
to aTreeSet
will throw aNullPointerException
at runtime becauseTreeSet
requires elements to be comparable for sorting, andnull
cannot be compared. -
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()); } }
Answer
Runtime error
Explanation: Initializing a
Vector
with a negative initial capacity will throw anIllegalArgumentException
at runtime. -
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); } }
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’sremove()
method. -
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()); } }
Answer
Runtime error
Explanation: Modifying a
HashSet
while iterating over it will throw aConcurrentModificationException
at runtime. -
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)); } }
Answer
Runtime error
Explanation: The
get(int index)
method will throw anIndexOutOfBoundsException
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. -
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); } }
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]
. -
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 + " "); } } }
Answer
Runtime error
Explanation: The code attempts to cast an
Integer
object (2
) to aString
, which will throw aClassCastException
at runtime. To avoid this, ensure that all elements are of the same type or handle casting appropriately.
Slightly harder MCQs
-
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); } }
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. -
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); } }
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]
. -
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); } }
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]
. -
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); } }
Answer
[5, 10, 20]
Explanation:
TreeSet
maintains a sorted order and does not allow duplicate elements. The final set is[5, 10, 20]
. -
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); } }
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]
. -
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()); } }
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. -
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); } }
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]
. -
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); } }
Answer
[Apple, Banana, Mango]
Explanation:
TreeSet
stores elements in a natural sorted order. The final set is[Apple, Banana, Mango]
. -
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); } }
Answer
[0, 1, 3]
Explanation: The code inserts
0
at the beginning of the list, and then removes the element at index2
(which is2
), resulting in[0, 1, 3]
. -
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")); } }
Answer
true
Explanation:
HashSet
allows only unique elements, and thecontains
method checks if an element exists in the set. Since “banana” is in the set, the output istrue
. -
Given a
Student
class with a constructor that initializes thename
andage
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()); } }
Answer
3
Explanation: The code adds three
Student
objects to theArrayList
, so the size of the list is 3. -
Given a
Student
class with aname
field and a methodgetName()
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()); } }
Answer
Eve
Explanation:
addFirst
inserts the student “Eve” at the beginning of the list, sogetFirst().getName()
returns “Eve”. -
Given a
Student
class with fieldsname
andage
, 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()); } }
Answer
2
Explanation: If the
Student
class does not overrideequals
andhashCode
, the twoStudent
objects with the same data are treated as different objects. So, the size of the set is 2. -
Given a
Student
class with fieldsname
andage
, 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); } }
Answer
Compilation error
Explanation:
TreeSet
requires elements to be comparable, so theStudent
class must implementComparable
or provide aComparator
when creating theTreeSet
. -
Given a
Student
class with fieldsname
andage
, 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()); } }
Answer
2
Explanation: The code removes the student at index 1, so the size of the
Vector
becomes 2. -
Given a
Student
class with fieldsname
andgrade
, 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() + " "); } } }
Answer
Alice Bob Charlie
Explanation:
LinkedHashSet
maintains the insertion order, so the elements are printed in the order they were added. -
Given a
Student
class with fieldsname
andgrade
, 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()); } }
Answer
true
Explanation: The
clear()
method removes all elements from the list, making it empty. TheisEmpty()
method returnstrue
. -
Given a
Student
class with fieldsname
andmarks
, 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() + " "); } } } }
Answer
Alice Bob
Explanation: The code prints the names of students with marks greater than 80, so “Alice” and “Bob” are printed.
-
Given a
Student
class with fieldsname
andmarks
, 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()); } }
Answer
Bob
Explanation: The custom comparator sorts students by marks in descending order, so
first()
returns “Bob”, who has the highest marks. -
Given a
Student
class with fieldsname
andmarks
, 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()); } }
Answer
2
Explanation: If the
Student
class does not overrideequals
andhashCode
, theremove
method won’t find a match, and the size remains unchanged at 3. If it does, the size will be 2. -
Given a
Book
class with fieldstitle
andauthor
, 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()); } }
Answer
3
Explanation: The code adds three
Book
objects to theArrayList
, so the size of the list is 3. -
Given a
Movie
class with fieldstitle
andyear
, 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()); } }
Answer
Interstellar
Explanation:
addFirst
inserts the movie “Interstellar” at the beginning of the list, sogetFirst().getTitle()
returns “Interstellar”. -
Given a
Person
class with fieldsname
andage
, 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()); } }
Answer
2
Explanation: If the
Person
class does not overrideequals
andhashCode
, the twoPerson
objects with the same data are treated as different objects. So, the size of the set is 2. -
Given a
Song
class with fieldstitle
andartist
, 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); } }
Answer
Compilation error
Explanation:
TreeSet
requires elements to be comparable, so theSong
class must implementComparable
or provide aComparator
when creating theTreeSet
. -
Given a
Product
class with fieldsname
andprice
, 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()); } }
Answer
2
Explanation: The code removes the product at index 1, so the size of the
Vector
becomes 2. -
Given a
City
class with fieldsname
andpopulation
, 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() + " "); } } }
Answer
New York Los Angeles Chicago
Explanation:
LinkedHashSet
maintains the insertion order, so the elements are printed in the order they were added. -
Given an
Animal
class with fieldsspecies
andage
, 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()); } }
Answer
true
Explanation: The
clear()
method removes all elements from the list, making it empty. TheisEmpty()
method returnstrue
. -
Given a
Car
class with fieldsmake
andyear
, 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() + " "); } } } }
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.
-
Given a
Gadget
class with fieldsname
andprice
, 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()); } }
Answer
Laptop
Explanation: The custom comparator sorts the gadgets by price in ascending order, so the last element (highest price) is “Laptop”.
-
Given a
Course
class with fieldscourseName
andduration
, 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()); } }
Answer
Python
Explanation: The
removeLast()
method removes the last course in the list, leaving “Java” and “Python”. ThegetLast()
method then returns the course name of the last remaining course, “Python”.
Tricky MCQs
-
Given a
Developer
class with fieldsname
andexperience
, and assumingequals
andhashCode
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))); } }
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. -
Given an
Employee
class with fieldsid
anddepartment
, and assumingequals
andhashCode
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()); } }
Answer
3
Explanation: Since
equals
andhashCode
are overridden, duplicates based on the sameid
anddepartment
are not added. So the size is 3. -
Given a
Course
class with fieldstitle
andduration
, and assumingCourse
implementsComparable<Course>
based ontitle
, 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()); } }
Answer
2
Explanation: Since
Course
objects are compared based ontitle
, “Math” is considered a duplicate, and only two unique courses (“Math” and “Science”) are added. -
Given a
Building
class with fieldsname
andheight
, 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()); } }
Answer
2
Explanation: Without overriding
equals
andhashCode
,remove
does not find the object in the list, so the size remains 2. -
Given a
Gadget
class with fieldsmodel
andprice
, and assumingequals
andhashCode
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()); } }
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.
-
Given a
Team
class with fieldsname
andrank
, 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()); } }
Answer
Delta
Explanation: The
add(1, new Team("Delta", 4))
inserts “Delta” at index 1, pushing the other elements to the right. -
Given a
Library
class with fieldsname
andbooksCount
, and assumingLibrary
implementsComparable<Library>
based onbooksCount
, 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()); } }
Answer
East
Explanation: The
TreeSet
orders libraries bybooksCount
, and the one with the smallestbooksCount
is “East”. -
Given a
Student
class with fieldsname
andgrade
, and assumingequals
andhashCode
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"))); } }
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, socontains
returnsfalse
. -
Given a
Country
class with fieldsname
andpopulation
, and assumingequals
andhashCode
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()); } }
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.
-
Given a
Product
class with fieldsname
andprice
, and assumingProduct
implementsComparable<Product>
based onprice
, 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()); } }
Answer
Tablet
Explanation: The
TreeSet
orders products byprice
, andpollFirst()
retrieves and removes the lowest-priced product, which is “Tablet”.