Java Q Unit2
Java Q Unit2
Qns 1. What is collection Framework. List any two goals of collection Framework.
The Collection Framework in Java is a set of classes and interfaces in the [Link] package that provides a unified
architecture for storing, manipulating, and processing groups of objects.
1. Reduce Programming Effort
• Provides ready-made data structures and algorithms
• No need to implement from scratch (like arrays, sorting, searching)
2. Increase Performance
• Offers efficient implementations of data structures
• Allows choosing the best structure (e.g., ArrayList vs LinkedList)
Page :1
Advanced Java Unit 2
Qns 6. Write the purpose of Array class.
The purpose of the Array class in programming is to provide a way to store, manage, and manipulate a collection
of elements of the same type efficiently. Arrays allow you to handle multiple values under a single variable name,
access elements using an index, and perform operations like searching, sorting, and iterating over elements
Qns 11. List any four exceptions thrown in the context of collections
NullPointerException – Thrown when you try to add null to a collection that does not allow null elements (e.g.,
TreeSet or Hashtable).
ClassCastException – Thrown when attempting to add an element of the wrong type to a collection that enforces type
restrictions (common with sorted collections like TreeSet).
IllegalArgumentException – Thrown when an invalid argument is passed to a method, for example, specifying a
negative initial capacity for an ArrayList.
ConcurrentModificationException – Thrown when a collection is modified while iterating using an iterator
(except through the iterator’s own remove() method).
Page :2
Advanced Java Unit 2
retainAll() :- Keeps only the elements that are also present in another collection.
List<Integer> list1 = new ArrayList<>([Link](1, 2, 3, 4));
List<Integer> list2 = [Link](2, 3, 5);
[Link](list2);
[Link](list1); // [2, 3]
Qns 14. What is the purpose of the NavigableSet interface in the Java Collections Framework.
The NavigableSet interface was added by Java SE 6. It extends SortedSet and declares the behavior of a collection that
supports the retrieval of elements based on the closest match to a given value or values. NavigableSet is a generic
interface that has this declaration: interface NavigableSet<E
A sorted collection of unique elements
With the ability to navigate, search, and retrieve nearby elements quickly
Qns 15. How you can add or remove element to/from the first, last using LinkedList Class.
LinkedList<Integer> list = new LinkedList<>();
[Link](10); // [10]
[Link](20); // [10, 20]
[Link](5); // [5, 10, 20]
Qns 19. What is the purpose of push() and pop() methods of Deque interface?
push()
• Adds an element at the front of the deque.
• Equivalent to pushing an element onto a stack.
pop()
• Removes and returns the first element of the deque.
• Equivalent to popping the top element from a stack.
Qns 21. What are the syntax/signatures of the two overloaded toArray() methods in the ArrayList class?
1. Object[] toArray()
public Object[] toArray()
• Returns an array of type Object[]
• Contains all elements in the list
2. <T> T[] toArray(T[] a)
public <T> T[] toArray(T[] a)
• Returns an array of the same type as the input array
• Provides type safety (no casting needed)
Qns 22. What is the difference between the HashSet() and HashSet(int capacity) constructors?
HashSet<String> set = new HashSet<>();
• Uses default initial capacity = 16
• Uses default load factor = 0.75
HashSet<String> set = new HashSet<>(50);
• Sets a custom initial capacity
• Still uses default load factor = 0.75
Qns 23. What is the purpose of the float fillRatio parameter in the HashSet(int capacity, float fillRatio) constructor?
uses the fillRatio parameter (more commonly called load factor) to control when the underlying hash table should
resize.
How full the set can get before it increases its capacity (rehashes).
Qns 24. What is the primary advantage of using a TreeSet over other Set implementations like HashSet?
Use TreeSet when:
You need sorted data
Page :4
Advanced Java Unit 2
You need range or navigation operations
Use HashSet when:
You only care about fast insertion and lookup
Order doesn’t matter
Qns 25. What is the main difference between using a foreach loop and an Iterator to traverse the elements of a
Collection in Java?
Foreach Loop : Works on any Collection and is the simplest way to iterate.
• Clean and concise syntax
• Automatically uses an iterator internally
• Best for read-only traversal
Qns 26. What is the purpose of the RandomAccess interface in Java collections?
The RandomAccess interface in Java is a marker interface (it has no methods) used to indicate that a list supports
fast (constant-time) random access.
Qns 29. What is the purpose of using a Comparator with TreeSet and TreeMap in Java?
A Comparator lets you control how elements are ordered, instead of relying on their natural order.
Page :5
Advanced Java Unit 2
Qns 30. List any four overloaded forms/signatures of the binarySearch() method with their proper syntax.
The binarySearch( ) method uses a binary search to find a specified value. This method
must be applied to sorted arrays. Here are some of its forms. (Java SE 6 adds several others.)
static int binarySearch(byte array[ ], byte value)
static int binarySearch(char array[ ], char value)
static int binarySearch(double array[ ], double value)
static int binarySearch(float array[ ], float value)
static int binarySearch(int array[ ], int value)
static int binarySearch(long array[ ], long value)
static int binarySearch(short array[ ], short value)
static int binarySearch(Object array[ ], Object value)
static <T> int binarySearch(T[ ] array, T value, Comparator<? super T> c)
Qns 32. What is the relationship between the Dictionary class and the Map interface in Java?
1. Dictionary Class
• It is an abstract class in [Link].
• Legacy class: Introduced in early Java (JDK 1.0).
• Stores key-value pairs.
• Subclasses include Hashtable.
• Does not implement the Map interface, because it predates it.
• Considered obsolete, and modern code favors Map implementations.
2. Map Interface
• Part of the Collections Framework.
• Defines standard methods for key-value collections: put(), get(), remove(), containsKey(), keySet(), etc.
• Implemented by modern classes like HashMap, TreeMap, and LinkedHashMap.
Provides more flexibility, better API, and integration with collections
33. What are two advantages of using the MVC architecture in Java applications?
1. Separation of Concerns
• The application is divided into three components:
o Model → Manages data and business logic.
o View → Handles the user interface and presentation.
o Controller → Handles user input and communicates between Model and View.
• Changes in one component (like UI redesign) do not affect business logic, making development and
maintenance easier.
2. Reusability and Maintainability
• Model and Controller can be reused across different Views (e.g., same data logic for GUI or web interface).
• Makes testing and debugging easier, because you can test each component independently
Page :6
Advanced Java Unit 2
Model-View-Controller (MVC) is a software architectural pattern used to separate an application into three
interconnected components, making it easier to manage, maintain, and scale. It’s widely used in Java applications,
especially in GUI and web applications.
Qns 35. What are two responsibilities of the View component in MVC?
Display Data to the User:
The View is responsible for presenting data from the Model in a readable and interactive way. It defines how
information is rendered, such as generating HTML, GUI elements, or charts, depending on the application.
Receive User Input (Indirectly):
While the View doesn’t process business logic, it captures user input (like clicks, typing, or gestures) and sends it to
the Controller. This ensures the separation of concerns: the View handles presentation, the Controller handles input
logic, and the Model handles data.
Qns 36. What are the primary roles of the Controller component in the MVC architecture?
1. Handling User Input:
2. Updating the Model:
3. Updating the View:
4. Coordinating Application Flow:
Qns 37. What are the responsibilities of the Model component in handling data and business logic?
1. Managing Application Data:
2. Implementing Business Logic:
3. Notifying Views of Data Changes:
4. Data Integrity and Validation:
(4 to 6 marks)
Qns 2. List any five methods of Collection interface with its purpose.
Objects are added to a collection by calling add( ). Notice that add( ) takes an argument of type E, which means that
objects added to a collection must be compatible with the type of data expected by the collection.
You can add the entire contents of one collection to another by calling addAll( ).
You can remove an object by using remove( ).
To remove a group of objects, call removeAll( ).
You can remove all elements except those of a specified group by calling retainAll( ).
Page :7
Advanced Java Unit 2
To empty a collection, call clear( ).
You can determine whether a collection contains a specific object by calling contains( ).
To determine whether one collection contains all the members of another, call containsAll( ).
You can determine when a collection is empty by calling isEmpty( ).
The number of elements currently held in a collection can be determined by calling size( ).
The toArray( ) methods return an array that contains the elements stored in the invoking collection.
Qns 3. What are the basic interfaces of Java Collections Framework? Discuss the appropriate use of any four
interfaces
Basic Interfaces of Java Collections Framework
1. Collection (root interface) : The base interface for most collection types (except Map). It defines common
operations like add, remove, size, and iteration.
2. List : An ordered collection (sequence) that allows duplicate elements and positional access.
3. Set : A collection that does not allow duplicate elements.
4. Queue : A collection designed for holding elements prior to processing, typically in FIFO (First-In-First-Out)
order.
5. Deque (Double-Ended Queue) : Allows insertion and removal of elements from both ends.
6. Map (separate from Collection hierarchy) : Stores key-value pairs, where keys are unique.
Appropriate Use of Any Four Interfaces
1. List
• You need an ordered collection
• Duplicates are allowed
• You require index-based access
Examples:
• Storing a list of student names
• Maintaining a playlist
Common implementations: ArrayList, LinkedList
2. Set
• You need to store unique elements only
• No duplicates should be allowed
Examples:
• Storing unique user IDs
• Removing duplicates from a collection
Common implementations: HashSet, LinkedHashSet, TreeSet
3. Queue
• You need FIFO processing
• Elements are processed in the order they arrive
Examples:
• Task scheduling
• Printer job queue
Common implementations: PriorityQueue, LinkedList
4. Map
• You need to store key-value pairs
• Fast lookup using a key is required
Examples:
• Storing student ID → student record
• Caching data
Page :8
Advanced Java Unit 2
Qns 4. List any five methods of List interface with its purpose.
Qns 7. List any five methods of Queue interface with its purpose.
Page :9
Advanced Java Unit 2
Qns 8. List any five methods of Deque interface with its purpose.
// Demonstrate ArrayList.
import [Link].*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
[Link]("Initial size of al: " +
[Link]());
// Add elements to the array list.
[Link]("C"); [Link]("A"); [Link]("E"); [Link]("B"); [Link]("D"); [Link]("F"); [Link](1, "A2");
[Link]("Size of al after additions: " +
[Link]());
// Display the array list.
[Link]("Contents of al: " + al);
// Remove elements from the array list.
[Link]("F");
[Link](2);
[Link]("Size of al after deletions: " +
[Link]());
[Link]("Contents of al: " + al);
}
}
The output from this program is shown here:
Page :10
Advanced Java Unit 2
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Qns 10. Write a Java program that demonstrates how to convert an ArrayList to an array using the toArray() method
When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list.
You can do this by calling toArray( ), which is defined by Collection. Several reasons exist why you might want to
convert a collection into an array, such as:
• To obtain faster processing times for certain operations
• To pass an array to a method that is not overloaded to accept a collection
• Tointegrate collection-based code with legacy code that does not understand collections
Whatever the reason, converting an ArrayList to an array is a trivial matter. As explained earlier, there are two
versions of toArray( ), which are shown again here for your convenience:
Object[ ] toArray( )
<T> T[ ] toArray(T array[ ])
Java program to convert an ArrayList to an array using the toArray() method.
import [Link].*;
// Create an ArrayList
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
Qns 11. Write a Java program that demonstrates the usage of the LinkedList class from the Java Collections
Framework.
The LinkedList Class
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and
Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that
has this declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold. LinkedList has the two constructors
shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
// Demonstrate LinkedList.
Page :11
Advanced Java Unit 2
import [Link].*;
class LinkedListDemo {
public static void main(String args[]) {
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
[Link]("F");
[Link]("B");
[Link]("D");
[Link]("E");
[Link]("C");
[Link]("Z");
[Link]("A");
[Link](1, "A2");
[Link]("Original contents of ll: " + ll);
// Remove elements from the linked list.
[Link]("F");
[Link](2);
[Link]("Contents of ll after deletion: "+ ll);
// Remove first and last elements.
[Link]();
[Link]();
[Link]("ll after deleting first and last: "+ ll);
// Get and set a value.
String val = [Link](2);
[Link](2, val + " Changed");
[Link]("ll after change: " + ll);
}
}
Qns 12. Explain four constructors of the HashSet class from the Java Collections Framework, including their
parameters
The HashSet Class
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
HashSet is a generic class that has this declaration:
class HashSet<E>
Here, E specifies the type of objects that the set will hold.
The following constructors are defined:
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
The first form constructs a default hash set. The second form initializes the hash set by using the elements of c. The
third form initializes the capacity of the hash set to capacity. (The default capacity is 16.) The fourth form initializes
both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments. The fill ratio must be
between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the
number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For
constructors that do not take a fill ratio, 0.75 is used. HashSet does not define any additional methods beyond those
provided by its super classes and interfaces.
// Demonstrate iterators.
import [Link].*;
class IteratorDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
// Add elements to the array list.
[Link]("C");
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F");
// Use iterator to display contents of al.
[Link]("Original contents of al: ");
Iterator<String> itr = [Link]();
while([Link]()) {
String element = [Link]();
[Link](element + " ");
} } }
Qns 14. Explain the usage of the for-each loop in Java when working with collections. Compare and contrast the for-
each loop with the traditional approach of using an Iterator.
For-Each Loop in Java
The for-each loop is mainly used with:
• Arrays
• Classes implementing the Iterable interface (e.g., ArrayList, HashSet)
import [Link].*;
List<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
for (String name : names) {
[Link](name);
}
• The for-each loop:
• Uses an Iterator behind the scenes
• Calls:
o iterator()
o hasNext()
o next()
• So it’s essentially a simplified syntax over Iterator
Traditional Approach Using Iterator
Iterator<String> it = [Link]();
while ([Link]()) {
String name = [Link]();
[Link](name);
}
Page :13
Advanced Java Unit 2
Use For-Each Loop When:
You just need to read elements
No modification required
Simpler, cleaner code is preferred
Use Iterator When:
You need to remove elements أثناءiteration
You need more control over traversal
Working with complex iteration logic
Qns 15. Explain how to store objects of user-defined classes in Java collections like ArrayList
For the sake of simplicity, the foregoing examples have stored built-in objects, such as String or Integer, in a
collection. Of course, collections are not limited to the storage of built-in objects. Quite the contrary. The power of
collections is that they can store any type of object, including objects of classes that you create. For example, consider
the following example that uses a LinkedList to store mailing addresses
// A simple mailing list example.
import [Link].*;
class Address {
private String name;
private String street;
private String city;
private String state;
private String code;
Address(String n, String s, String c,
String st, String cd) {
name = n;
street = s;
city = c;
state = st;
code = cd;
}
public String toString() {
return name + "\n" + street + "\n" +
city + " " + state + " " + code;
}
}
class MailList {
public static void main(String args[]) {
LinkedList<Address> ml = new LinkedList<Address>();
// Add elements to the linked list.
[Link](new Address("J.W. West", "11 Oak Ave",
"Urbana", "IL", "61801"));
[Link](new Address("Ralph Baker", "1142 Maple Lane",
"Mahomet", "IL", "61853"));
[Link](new Address("Tom Carlton", "867 Elm St",
"Champaign", "IL", "61820"));
// Display the mailing list.
for(Address element : ml)
[Link](element + "\n");
[Link]();
}
}
Page :14
Advanced Java Unit 2
Feature Vector ArrayList
Thread Safety Synchronized (thread-safe) Not synchronized (not thread-safe)
Slower in single-threaded environments due to
Performance Faster in single-threaded environments
synchronization overhead
Legacy class (from early Java, before Collections
Legacy Status Part of the Java Collections Framework
Framework)
Growth
Doubles its size when capacity is exceeded Increases by 50% when capacity is exceeded
Strategy
Has legacy methods like addElement(), elementAt(), Uses modern collection methods like add(),
Methods
removeElement() get(), remove()
Provides Enumeration (legacy) in addition to
Iterator Provides only Iterator and ListIterator
Iterator
Useful if thread-safety is required and backward Preferred in most modern applications for
Use Case
compatibility matters general-purpose use
Qns 17. Write the usage of any four methods of Map interface
Page :15
Advanced Java Unit 2
Qns 19. Write a Java program that demonstrates the usage of the HashMap class from the Java Collections Framework
The HashMapclass extends AbstractMap and implements the Map interface. It uses a hash table to store the map. This
allows the execution time of get( ) and put( ) to remain constant even for large sets. HashMap is a generic class that
has this declaration:
class HashMap<K, V>
import [Link].*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map.
HashMap<String, Double> hm = new HashMap<String, Double>();
// Put elements to the map
[Link]("John Doe", new Double(3434.34));
[Link]("Tom Smith", new Double(123.22));
[Link]("Jane Baker", new Double(1378.00));
[Link]("Tod Hall", new Double(99.22));
[Link]("Ralph Smith", new Double(-19.08));
// Get a set of the entries.
Set<[Link]<String, Double>> set = [Link]();
// Display the set.
for([Link]<String, Double> me : set) {
[Link]([Link]() + ": ");
[Link]([Link]());
}
[Link]();
// Deposit 1000 into John Doe's account.
double balance = [Link]("John Doe");
[Link]("John Doe", balance + 1000);
[Link]("John Doe's new balance: " +
[Link]("John Doe"));
}
}
Output from this program is shown here (the precise order may vary):
Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Tod Hall: 99.22
Jane Baker: 1378.0
John Doe’s new balance: 4434.34
Qns 20. Write a Java program that demonstrates the usage of a custom Comparator for sorting strings in reverse order.
Using a Comparator
The following is an example that demonstrates the power of a custom comparator. It implements the compare( )
method for strings that operates in reverse of normal. Thus, it causes a tree set to be stored in reverse order.
// Use a custom comparator.
import [Link].*;
// A reverse comparator for strings.
class MyComp implements Comparator<String> {
public int compare(String a, String b) {
String aStr, bStr;
aStr = a;
bStr = b;
// Reverse the comparison.
return [Link](aStr);
}
Page :16
Advanced Java Unit 2
// No need to override equals.
}
class CompDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet<String> ts = new TreeSet<String>(new MyComp());
// Add elements to the tree set.
[Link]("C");
[Link]("A");
[Link]("B");
[Link]("E");
[Link]("F");
[Link]("D");
// Display the elements.
for(String element : ts)
[Link](element + " ");
[Link]();
}
}
As the following output shows, the tree is now stored in reverse order:
FEDCBA
Qns 22. Write a program to convert a given array into a collection with the asList() method.
Java program that converts an array into a collection using the asList() method from Arrays.
import [Link].*;
Page :17
Advanced Java Unit 2
// Step 3: Display the collection
[Link]("Array elements:");
for (String s : arr) {
[Link](s);
}
[Link]("\nConverted Collection (List):");
for (String s : list) {
[Link](s);
}
} }
Qns 23. Explain any four legacy methods of vector
In Java, Vector is a legacy class from [Link] (introduced before the Java Collections Framework). Although it’s
mostly replaced by ArrayList now, it still exists and provides some legacy methods that are not part of modern
collection interfaces like List. Here are four important legacy methods of Vector:
1. addElement(E obj)
• Adds an element to the end of the vector.
• Similar to add() in ArrayList, but comes from the legacy API.
Vector<String> vec = new Vector<>();
[Link]("Apple");
[Link]("Banana");
[Link](vec); // [Apple, Banana]
2. elementAt(int index)
• Returns the element at the specified index.
• Similar to get(int index).
String fruit = [Link](0);
[Link](fruit); // Apple
3. removeElement(Object obj)
• Removes the first occurrence of the specified object.
• Returns true if the element was found and removed.
[Link]("Apple");
[Link](vec); // [Banana]
4. insertElementAt(E obj, int index)
• Inserts an element at a specific position, shifting subsequent elements.
• Legacy alternative to add(index, obj).
Qns 24. Explain the roles and responsibilities of the Model, View, and Controller components in the MVC
architecture.
The Model–View–Controller (MVC) architecture separates an application into three interconnected components,
each with a clear responsibility. This separation helps keep code organized, scalable, and easier to maintain.
1. Model (Data & Business Logic)
The Model represents the core of the application.
• Responsibilities:
o Manages the application’s data (e.g., database records, objects).
o Contains business logic (rules, calculations, validations).
o Handles data storage and retrieval (e.g., from a database or API).
o Notifies other components (usually the View) when data changes.
2. View (User Interface)
The View is what the user sees and interacts with.
• Responsibilities:
o Displays data provided by the Model.
o Renders the UI (User Interface) (HTML pages, UI screens, etc.).
o Updates the display when the Model changes.
o Sends user actions (like clicks or input) to the Controller.
Page :18
Advanced Java Unit 2
3. Controller (Input & Coordination)
The Controller acts as a bridge between the Model and the View.
• Responsibilities:
o Handles user input (e.g., button clicks, form submissions).
o Interprets input and decides what to do.
o Updates the Model based on user actions.
o Selects or updates the View to display the results.
Qns 25. Explain the flow of execution when a user interacts with an MVC-based Java web application. Walk through
the steps involved, starting from the user's request, the role of the controller, the interaction with the model and view,
and finally, the response sent back to the user.
When a user interacts with an MVC-based Java web application (for example, using frameworks like Spring MVC or
traditional Servlets/JSP), the execution follows a structured flow. Here’s a step-by-step walkthrough from request to
response:
1. User Sends a Request
• The process begins when the user performs an action in the browser (e.g., clicking a link or submitting a
form).
• This generates an HTTP request (GET/POST) sent to the web server.
2. Request Reaches the Front Controller
• In many Java MVC frameworks, a Front Controller (like a DispatcherServlet in Spring MVC) acts as the
central entry point.
• It:
o Intercepts all incoming requests.
o Decides which specific controller should handle the request.
3. Controller Handles the Request
• The appropriate Controller receives the request.
• Responsibilities at this stage:
o Extract request parameters (form data, query params).
o Perform basic validation if needed.
o Decide what business operation is required.
• The controller does not implement business logic itself—it delegates that work.
4. Controller Interacts with the Model
• The controller calls the Model (often via service classes or DAO layers).
• The Model:
o Processes business logic.
o Interacts with the database (CRUD operations).
o Applies rules, calculations, or validations.
• The Model returns the result (data or objects) back to the controller.
5. Controller Prepares the Response
• The controller:
o Receives data from the Model.
o Adds this data to a structure (e.g., Model, ModelMap, or request attributes).
o Selects which View should render the response (e.g., a JSP page).
6. View Resolution
• A View Resolver determines the actual view file (e.g., maps a logical name like "home" to /WEB-
INF/views/[Link]).
7. View Renders the Data
• The View
o Retrieves data passed by the controller.
o Generates dynamic content (HTML, JSON, etc.).
o Does not contain business logic—only presentation logic.
8. Response Sent Back to User
• The rendered output is returned as an HTTP response.
• The browser receives and displays the result to the user.
Page :19