Ajava - II Unit
Ajava - II Unit
2 marks:
1. What is Collection Framework? List any two goals of collection Framework.
The Collections Framework is a sophisticated hierarchy of interfaces and classes that provide state-
of-the-art technology for managing groups of objects. Two goals include:
• The framework had to be high-performance.
• Extending and/or adapting a collection had to be easy.
2. What are the benefits of using the Collections Framework?
It is one of java’s most powerful subsystems. It merits close attention by all programmers.
Because java.util contains a wide array of functionality, it is quite large.
3. List any two collection classes with its purpose.
• AbstractCollection : Implements most of the Collection interface
• ArrayList – Implements dynamic array by extending AbstractList.
29. What is the purpose of using a Comparator with TreeSet and TreeMap in Java?
Both TreeSet and TreeMap store elements in sorted order. If you want to order elements a different
way, then specify a Comparator when you construct the set or map. Doing so gives you the ability
to govern precisely how plements are stored within sorted collections and maps.
30. List any four overloaded forms/signatures of the binarySearch() method with their proper
syntax.
static int binarySearch(byte array[ ], byte value)
static int binarySearch(char array[ ], char value)
static int binarySearch(float array[ ], float value)
static int binarySearch(int array[ ], int value)
31. Differentiate Vector and Arrays.
Vectors are dynamic in size. They can grow and shrink as needed when elements are added or
removed. They are synchronized, meaning they are thread-safe.
Arrays have a fixed size, which means you must specify the number of elements at the time of array
creation. They are not synchronized.
32. What is the relationship between the Dictionary class and the Map interface in Java?
Dictionary is an abstract class that represents a key/value storage repository and operates much like
Map. Given a key and value, you can store the value in a Dictionary object. Once the value is
stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list
of key/value pairs. Although not currently deprecated, Dictionary is classified as obsolete, because
it is fully superseded by Map.
33. What are two advantages of using the MVC architecture in Java applications?
• Separation of Concerns: MVC promotes a clear separation of concerns between the model, view,
and controller components.
• Code Reusability: By separating the concerns into distinct components, code reuse becomes
more feasible.
3. What are the basic interfaces of Java Collections Framework? Discuss the appropriate use
of any four interfaces.
The Collections Framework defines several interfaces. They are Collection, List, NavigableSet,
Queue, Deque, Set, SortedSet.
Collection : The Collection interface is the foundation upon which the Collections Framework is
built because it must be implemented by any class that defines a collection. It is declared as:
interface Collection<E>
Here, E specifies the type of objects that the collection will hold.
List: The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements. Elements can be inserted or accessed by their position in the list, using this
declaration: interface List<E>
Here, E specifies the type of objects that the list will hold.
Queue: The Queue interface extends Collection and declares the behavior of a queue, which is
often a first-in, first-out list. It is declared as: interface SortedSet<E>
Here, E specifies the type of objects that the collection will hold.
Deque: The Deque interface extends Queue and declares the behavior of a double-ended queue.
Deque is a generic interface that has this declaration: interface Deque<E>
10. Write a Java program that demonstrates the usage of the LinkedList class from the Java
Collections Framework.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C");
ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
// Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
// Get and set a value.
String val = 11.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
Output: Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
11. Explain four constructors of the HashSet class from the Java Collections Framework,
including their parameters.
HashSet( ) constructs a default hashset. It creates an empty HashSet object with a default capacity
of 16.
HashSet(Collection<? extends E> c) initializes the hash set by using the elements of c.
HashSet(int capacity) allows you to specify the initial capacity of the HashSet. The initial capacity
defines the initial size of the underlying hash table used by the set.
HashSet(int capacity, float fillRatio) 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.
12. What is an iterator? Explain with an example.
Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the
collection. By using this iterator object, you can access each element in the collection, one element
at a time. In general, to use an iterator to cycle through the contents of a collection, follow these
steps:
i. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
ii. Setup a loop to make a call to hasNext( ).Have the loop iterate as long as hasNext( )returns true.
iii. Within the loop, obtain each element by calling next( ).
Example:
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList<String> list = new ArrayList<>();
list.add("Apple"); list.add("Banana"); list.add("Cherry"); list.add("Date");
// Get an iterator for the list
Iterator<String> i = list.iterator();
// Use the iterator to traverse the list
while (i.hasNext()) {
String element = i.next();
System.out.println(element);
// Optionally remove an element during iteration
if (element.equals("Banana")) {
i.remove();
}
}
// Print the list after iteration
System.out.println("List after iteration and removal: " + list);
}
}
13. 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.
The for-each loop provides a concise and readable way to iterate over elements in a collection. It
simplifies the process of iterating through arrays and collections without the need for explicit
initialization, condition checking, or incrementing, making the code more readable and less error-
prone.
Feature for-each Loop Iterator
Syntax Concise More verbose
Readability More readable Less readable due to boilerplate code
Control Flow Limited control over collection Allows modification of collection structure
modification
Index Access No direct index access Can access element index using loop counter
Use Cases Simple iteration, focus on processing Complex iteration scenarios, modifying
elements collection
14. 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.
Example:
public class Person {
private String name;
private int age;
19. Write a Java program that demonstrates the usage of a custom Comparator for sorting
strings in reverse order.
import java.util.*;
class MyComp implements Comparator<String> {
public int compare(String a, String b) {
return a.compareTo(b); // Reverse the comparison.
}}
class Demo {
public static void main(String args[]) {
TreeSet<String> ts = new TreeSet<String>(new MyComp()); //TreeSet
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
for(String element : ts)
System.out.print(element + " "); // Display the elements.
System.out.println();
}}
As the following output shows, the tree is now stored in reverse order: F E DC BA
20. Write the usage of any 4 collection algorithms.
Collections.sort : The sort method sorts the elements of a list into their natural order or according to
a specified comparator.
Collections.binarySearch : The binarySearch method searches for a specified element in a sorted list
and returns the index of the element. The list must be sorted before performing the binary search.
Collections.shuffle : The shuffle method randomly permutes the elements of a list. This can be
useful for tasks like creating a deck of cards or randomizing elements.
Collections.max and Collections.min : The max and min methods find the maximum and minimum
elements in a collection according to their natural order or a specified comparator.
21. Write a program to convert a given array into a collection with the asList() method.
The asList() method returns a List that is backed by a specified array. Both the list and the array
refer to the same location.
import java.util.*;
public class ArrayToCollection {
public static void main(String[] args) {
// Given array
Integer[] array = {1, 2, 3, 4, 5};
// Convert array to a collection
List<Integer> list = Arrays.asList(array);
// Print the collection
System.out.println("Collection from array: " + list);
}
}
22. Explain any four legacy methods of vector.
void addElement(E element) The object specified by element is added to the vector.
int capacity( ) Returns the capacity of the vector.
Object clone( ) Returns a duplicate of the invoking vector.
E elementAt(int index) Returns the element at the location specified by index.
E firstElement( ) Returns the first element in the vector.
23. Explain the roles and responsibilities of the Model, View, and Controller components in
the MVC architecture.
• Model: The model represents the data and business logic of the application. It encapsulates the
application’s data and provides methods for accessing, manipulating, and updating that data. The
model component is independent of the user interface and focuses solely on the application’s
functionality.
• View: The view is responsible for rendering the user interface and displaying the data to the user.
It presents the data from the model to the user in a visually appealing and understandable way. The
view component does not contain any business logic but instead relies on the model for data.
• Controller: The controller acts as an intermediary between the model and the view. It handles
user input, processes user actions, and updates the model or view accordingly. The controller
interprets user actions and triggers the appropriate methods in the model or view. It ensures the
separation of concerns by keeping the view and mode independent of each other.
24. 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.
In Java programming, the Model comprises basic Java classes that encapsulate data and business
logic. The View is responsible for presenting the data to the user interface, while the Controller
consists of servlets that handle user requests. This clear separation of components enables the
following processing flow for user requests:
In the context of the server-client architecture, the process of handling a page request can be
described as follows:
A client, typically a web browser, initiates a request and sends it to the server-side controller.
The controller receives the request and interacts with the model component. It retrieves the
necessary data from the model, which may involve processing and manipulating the data as
required.
Once the controller has gathered the requested data, it transfers this data to the view layer.
The view layer, utilizing the provided data, generates the appropriate output or representation of
the requested page. Finally, the generated result is sent back to the client’s browser, completing the
request-response cycle.