0% found this document useful (0 votes)
2 views19 pages

Java Q Unit2

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Java Q Unit2

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Java Unit 2

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)

Qns 2. What are the benefits of using the Collections Framework?


1. Reduces Programming Effort
2. Improves Performance
3. Provides Standardized Architecture
4. Increases Code Reusability
5. Interoperability Between APIs
6. Built-in Algorithms Support

Qns 3. List any two collection classes with its purpose.


1. ArrayList
• Purpose: Used to store a dynamic array of elements
• Allows duplicate elements
• Maintains insertion order
• Provides fast access using index
2. HashSet
• Purpose: Used to store a collection of unique elements
• Does not allow duplicates
• Does not maintain insertion order
• Provides fast lookup

Qns 4. Write the differences between hasNext() and next() method.

Feature hasNext() next()


Purpose Checks if more elements are available Returns the next element
Return
boolean Element (Object / Generic type)
Type
Action Does not move the cursor Moves cursor to next element
Throws NoSuchElementException if no
Exception No exception
element

Qns 5. What is map? List any two Map interface


• A Map in Java is a data structure (part of the Collection Framework) that stores data in key–value pairs.
• Each key is unique
• Each key maps to exactly one value
• Values can be duplicated

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 7. Write the purpose of


a. fill()
fill() is used to quickly set all elements of a list to the same value. It's useful when you need to reset or initialize
lists with a single value.
b. copyOf()
It creates a new array of a specified length and copies elements from the original array into it.

Qns 8. Write the usage of iterator interface


An iterator offers a general-purpose, standardized way of accessing the elements within a collection, one at a time. Thus,
an iterator provides a means of enumerating the contents of a collection. Because each collection implements Iterator,
the elements of any collection class can be accessed through the methods defined by Iterator. Thus, with only small
changes, the code that cycles through a set can also be used to cycle through a list,

Qns 9. List any four interfaces provided by Collection Framework


List
Set
Queue
Map

Qns 10. Write any two uses of Generics.


Type Safety – Generics ensure that you can only store and retrieve objects of the specified type, reducing runtime
errors.
Code Reusability – You can write a single class or method that works with different types without duplicating code

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).

Qns 12. What is the usage of containsAll() and retainAll() methods?


containsAll() :- Checks whether one collection contains all elements of another collection.
List<Integer> list1 = [Link](1, 2, 3, 4);
List<Integer> list2 = [Link](2, 3);
boolean result = [Link](list2);
[Link](result); // true

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 13. List any four methods of List interface


I) add(E e) – Adds an element to the end of the list.
II) get(int index) – Returns the element at the specified position.
III) remove(int index) – Removes the element at the specified position.
IV) size() – Returns the number of elements in the list.

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]

[Link](); // removes 20 → [5, 10]


[Link](); // removes 5 → [10]

Qns 16. Differentiate headset() and tailset() methods


headSet() Returns a view of the portion of the set less than (or up to) a given element.
java TreeSet<Integer> ts = new TreeSet<>([Link](10,20,30,40)); [Link]([Link](30)); // Output:
[10,20]
tailSet() Returns a view of the portion of the set greater than or equal to a given element.
java TreeSet<Integer> ts = new TreeSet<>([Link](10,20,30,40)); [Link]([Link](30)); // Output:
[30,40]

Qns 17. Differentiate poll() and remove() methods of Queue interface

Feature poll() remove()


Purpose Retrieves & removes head Retrieves & removes head
Empty Queue Behavior Returns null Throws exception

Qns 18. List any four methods of deque interface


addFirst(E e) – Inserts the specified element at the front of the deque.
addLast(E e) – Inserts the specified element at the end of the deque.
removeFirst() – Removes and returns the first element of the deque.
Page :3
Advanced Java Unit 2
removeLast() – Removes and returns the last element of the deque.

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 20. How does an ArrayList differ from standard arrays?


Array
Fixed at the time of creation.
Can hold primitive types (int, char, etc.) directly.
Inserting or deleting elements requires manual shifting.
ArrayList
Dynamic; can grow or shrink automatically.
Can only hold objects (use wrapper classes for primitives, e.g., Integer for int).
Provides built-in methods like add(), remove(), clear().

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

The Iterator provides more control over traversal.


• Explicit control over iteration
• Can safely remove elements while iterating
• Useful for complex logic

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.

• Marker interface (no methods)


• Indicates fast indexed access
• Used for performance-aware coding
• Implemented by classes like ArrayList

Qns 27. How does a Map differ from a Collection in Java?


In Java, Map and Collection are both part of the Java Collections Framework, but they serve fundamentally different
purposes.
Collection → stores individual elements (values only)
List → ordered, allows duplicates
Set → no duplicates
Queue → ordered for processing
Map → stores key–value pairs
HashMap → unordered
TreeMap → sorted by keys
LinkedHashMap → insertion order

Qns 28. List any four Map classes


HashMap – Stores key-value pairs without any specific order. Allows one null key and multiple null values.
LinkedHashMap – Maintains insertion order of elements while storing key-value pairs.
TreeMap – Stores key-value pairs in sorted order according to the keys’ natural ordering or a custom comparator.
Hashtable – Legacy class (synchronized) that stores key-value pairs. Does not allow null keys or values.

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 31. Differentiate Vector and Arrays


• Arrays → Simple, fast, fixed-size, supports primitives.
• Vector → Flexible, resizable, thread-safe, only objects.

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

Qns 34. What is Model-View-Controller?

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 1. Explain the benefits of Generics in Collections Framework?


1. Type Safety
Generics ensure that only a specific type of object can be stored in a collection.
2. Eliminates Type Casting
Without generics, you must cast objects when retrieving them.
3. Compile-Time Error Detection
Errors are caught during compilation instead of runtime.
4. Improved Code Readability
Specifying types makes code easier to understand.
5. Reusability of Code
Generics allow you to write flexible, reusable methods and classes.
6. Better API Design
Libraries and frameworks can enforce type constraints clearly.
7. No Runtime Overhead
Generics use type erasure, meaning no extra memory or runtime cost.

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 6. Explain any four methods defined by NavigableSet interface

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.

Qns 9. With an example explain the usage of ArrayList ?


The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class that has this
declaration: class ArrayList<E>
Here, E specifies the type of objects that the list will hold. ArrayList supports dynamic arrays that can grow as needed.
In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that
you must knowinadvance howmanyelements an array will hold. But, sometimes, you may not know until run time
precisely how large an array you need.

// 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].*;

public class ArrayListToArrayExample {


public static void main(String[] args) {

// Create an ArrayList
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

// Convert ArrayList to Array using toArray()


String[] array = [Link](new String[0]);

// Display the array


[Link]("Array elements are:");
for (String item : array) {
[Link](item);
}
}
}

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.

Qns 13. What is an iterator? Explain with an example.


An Iterator is a design concept used in programming that allows you to traverse (go through) elements of a
collection one by one without exposing how that collection is implemented internally.
Page :12
Advanced Java Unit 2
In general, to use an iterator to cycle through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( )

// 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]();
}
}

Qns 16. Write how Vector is differ from ArrayList.

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

Qns 18. What is a map?


A map is an object that stores associations between keys and values, or key/value pairs. Given a key, you can find its
value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can
accept a null key and null values, others cannot. There is one key point about maps that is important to mention at the
outset: they don’t implement the Iterable interface. This means that you cannot cycle through a map using a for-each
style for loop. Furthermore, you can’t obtain an iterator to a map. However, as you will soon see, you can obtain a
collection-view of a map, which does allow the use of either the for loop or an iterator.
The Map Interfaces
Because the map interfaces define the character and nature of maps, this discussion of maps
begins with them. The following interfaces support maps:

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 21. Write the usage of any 4 collection algorithms.


In Java, collection algorithms refer to the utility methods provided by the [Link] class that operate on
collections like List, Set, and Map. These algorithms simplify tasks such as sorting, searching, shuffling, and
modifying collections.
1. Sorting
• [Link](List<T> list)
Sorts a list in natural order (e.g., numbers ascending, strings alphabetically).
2. Searching
• [Link](List<? extends Comparable<? super T>> list, T key)
Performs a binary search on a sorted list. Returns index or negative value if not found.
3. Reversing / Shuffling
• [Link](List<?> list) – Reverses the order of elements.
• [Link](List<?> list) – Randomly shuffles the elements.
• [Link](List<?> list, int distance) – Rotates elements by a distance.
4. Finding Extremes
• [Link](Collection<? extends T> c) – Finds the maximum element.
• [Link](Collection<? extends T> c) – Finds the minimum element.

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].*;

public class ArrayToCollection {


public static void main(String[] args) {
// Step 1: Create an array
String[] arr = {"Apple", "Banana", "Mango", "Orange"};

// Step 2: Convert array to List (Collection)


List<String> list = [Link](arr);

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

You might also like