0% found this document useful (0 votes)
10 views10 pages

Advanced Java Programming. MSC Cs 1

The document provides a comprehensive question bank for UNIT I on Design Patterns and Collection Framework, including multiple-choice questions, fill-in-the-blanks, short descriptive answers, and detailed explanations for various design patterns. It covers key concepts such as Factory Method, Singleton, Adapter, Decorator, and the Java Collection Framework, including comparisons of different collection types. The document serves as a study guide for understanding design patterns and their applications in Java.

Uploaded by

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

Advanced Java Programming. MSC Cs 1

The document provides a comprehensive question bank for UNIT I on Design Patterns and Collection Framework, including multiple-choice questions, fill-in-the-blanks, short descriptive answers, and detailed explanations for various design patterns. It covers key concepts such as Factory Method, Singleton, Adapter, Decorator, and the Java Collection Framework, including comparisons of different collection types. The document serves as a study guide for understanding design patterns and their applications in Java.

Uploaded by

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

Here’s a suggested **question bank + answers** for **UNIT I – DESIGN PATTERNS & COLLECTION

FRAMEWORK** with the requested distribution (MCQ, fill-in, 2-marks, 5-marks, 10-marks). You can
use/modify as per your needs.

---

## MCQ (5 questions)

1. Which design pattern ensures that a class has only one instance and provides a global point of access
to it?

A. Factory Method

B. Proxy

C. Singleton

D. Decorator

**Answer:** C

2. The Adapter pattern is primarily used to

A. Manage object creation

B. Provide a substitute object with same interface

C. Convert one interface into another

D. Control access to an object

**Answer:** C

3. Which of these is *not* an implementation of the `List` interface in Java?

A. ArrayList

B. LinkedList

C. HashSet
D. Vector

**Answer:** C

4. Which `Set` implementation maintains elements in sorted (natural) order?

A. HashSet

B. LinkedHashSet

C. TreeSet

D. PriorityQueue

**Answer:** C

5. What is the time complexity of `get(int index)` in an `ArrayList`?

A. O(1)

B. O(n)

C. O(log n)

D. O(n²)

**Answer:** A

---

## Fill in the Blanks (5 questions)

1. The __________ pattern allows creating new objects by copying an existing object.

**Answer:** Prototype

2. In Java Collections, the `HashMap` allows __________ null key(s).


**Answer:** one

3. The `Comparator` interface defines the method `__________` for ordering.

**Answer:** compare

4. The `ListIterator` interface supports __________ traversal (forward and backward).

**Answer:** bidirectional

5. `LinkedHashMap` maintains the __________ order of its entries.

**Answer:** insertion

---

## Two-marks (5 small descriptive / short answer)

1. Briefly explain the Factory Method pattern.

**Answer (2 marks):** The Factory Method provides an interface for creating objects, but lets
subclasses decide which class to instantiate. It decouples client code from concrete classes.

2. What is the difference between `Comparable` and `Comparator`?

**Answer (2 marks):**

* `Comparable` is implemented by a class to define its natural ordering via `compareTo(...)`.

* `Comparator` is a separate object used to define an ordering of objects (externally) via `compare(...)`.

3. What is a Proxy pattern in design patterns?


**Answer (2 marks):** The Proxy pattern provides a surrogate or placeholder for another object to
control access to it (e.g., lazy loading, access control, remote proxy).

4. When would you use a `TreeMap` instead of a `HashMap`?

**Answer (2 marks):** Use `TreeMap` when you need keys in sorted order (natural or via
comparator). `TreeMap` maintains sorted order; `HashMap` does not.

5. What is the difference between `ArrayList` and `LinkedList` in terms of performance for insertion and
access?

**Answer (2 marks):**

* **Access (get by index):** `ArrayList` is O(1), `LinkedList` is O(n).

* **Insertion/deletion in middle:** `LinkedList` is better (O(1) to insert once position found), while
`ArrayList` requires shifting elements (O(n)).

---

## Five-marks (5 questions)

1. Explain the Decorator pattern with example and advantages.

**Answer (5 marks):**

* **What:** The Decorator pattern attaches additional responsibilities dynamically to an object. It


provides a flexible alternative to subclassing for extending functionality.

* **Structure:** A `Component` interface, `ConcreteComponent`, an abstract `Decorator` class


implementing `Component` and holding a reference to a `Component`, and concrete decorators.

* **Example:** In Java IO, `BufferedInputStream` decorates an `InputStream` to add buffering.

* **Advantages:**
* More flexible than static inheritance

* You can combine multiple decorators at runtime

* Single Responsibility: each decorator handles one concern

* **Disadvantages:**

* Many small classes

* Harder to debug or understand dynamic composition

2. Describe the Template Method pattern. Show how it enforces algorithm structure.

**Answer (5 marks):**

* **What:** Template Method defines the skeleton of an algorithm in a base class, with some steps
deferred to subclasses.

* **Structure:** An abstract class defines a `final` method (template method) that calls abstract or
hook methods in certain steps. Subclasses override those steps.

* **Example:** In a game, a `Game` class has a template method `playGame()` that calls `initialize()`,
`startPlay()`, `endPlay()`. Subclasses implement those.

* **Benefits:** Enforces common structure, avoids code duplication, subclasses only change behavior
in specific steps.

3. Write a short note on Mediator pattern.

**Answer (5 marks):**

* **What:** Mediator defines an object that encapsulates how a set of objects interact; it promotes
loose coupling by preventing direct references between colleagues.

* **Structure:** A `Mediator` interface, concrete mediator, and colleague classes. Colleagues send
messages to mediator, not directly to each other.
* **Use case:** In a chat room, a mediator handles message routing between user objects.

* **Advantages:** Reduces coupling, easier maintenance, centralized control of interactions.

* **Disadvantages:** Mediator can become complex (God object).

4. Explain Proxy vs Decorator.

**Answer (5 marks):**

* Both use a similar structure (wrapping another object).

* **Proxy** controls access to the object (e.g., lazy loading, caching, security). Client may not know if
proxy or real object.

* **Decorator** adds new behavior or responsibilities to the object. Always forwards calls to the
wrapped object (possibly augmenting)

* Use proxy when controlling access is needed; use decorator when adding behavior is needed.

5. Explain how `HashSet` is implemented internally. Also mention complexity of basic operations.

**Answer (5 marks):**

* `HashSet` is backed by a `HashMap` internally. When you add an element, it inserts it as a key in a
`HashMap` with a dummy value.

* Internally, it uses hashing (via `hashCode()` and `equals()`) to place elements in buckets.

* Basic operations (`add`, `remove`, `contains`) are on average O(1), though worst-case (many
collisions) can degrade to O(n).

* `HashSet` does not guarantee order.

---

## Ten-marks (5 questions)
1. **(a)** Explain the Factory Method, Prototype, and Singleton design patterns in detail. **(b)**
Compare when to use each.

**(a)**

* **Factory Method:** Define an interface or abstract class for creating an object, but let subclasses
decide which class to instantiate. The client code uses the factory interface, not concrete classes.

* **Prototype:** Rather than creating new instances by `new`, clone a prototype object. Useful when
object creation is expensive and you can copy an existing prototype.

* **Singleton:** Ensures a class has only one instance and provides a global access point. Usually
implemented via a private constructor and a static method returning the single instance.

**(b)**

* Use **Factory Method** when you want to delegate instantiation to subclasses (extensibility) and
decouple client from concrete types.

* Use **Prototype** when new object creation is expensive and you can initialize a prototype and
clone it.

* Use **Singleton** when exactly one instance should exist (e.g. configuration manager, logging).

* You must be careful about threading, serialization, cloning, and testing (Singleton can be hard to
mock).

2. **(a)** Explain the structural patterns: Adapter, Decorator, Proxy. **(b)** Give a Java example for
each.

**(a)**

* **Adapter:** Converts one interface into another that clients expect. Allows incompatible interfaces
to work together.

* **Decorator:** Adds responsibilities/features to an object dynamically without altering its structure.

* **Proxy:** Provides a surrogate or placeholder for another object to control access (lazy, remote,
protection).
**(b)**

* **Adapter example:** Suppose you have an interface `Shape` with method `draw()`, and a legacy
class `LegacyRectangle` with `drawRectangle()`. An adapter `RectangleAdapter` implements `Shape` and
inside calls `drawRectangle()` on a `LegacyRectangle`.

* **Decorator example:** Java IO: `FilterInputStream`, `BufferedInputStream` decorate base


`InputStream` to add buffering.

* **Proxy example:** `ImageProxy` that loads a real `HighResolutionImage` only when `display()` is
called (lazy loading).

3. **(a)** Describe the Command pattern. (b) Illustrate with an example (e.g. remote control). (c)
Mention advantages and where it is useful.

**(a)** The Command pattern encapsulates a request as an object, letting you parameterize clients
with queues, requests, or operations. You separate the object that invokes the operation from the one
that knows how to perform it.

**(b)** Example: A remote control has buttons; each button is associated with a `Command` object
implementing `execute()`. Concrete commands wrap a receiver (e.g. `LightOnCommand` wraps a `Light`
object and in `execute()` calls `[Link]()`). The remote (“Invoker”) invokes `execute()`. You can also
support undo by storing commands and invoking `undo()`.

**(c)** Advantages:

* Decouples invoker and receiver

* Supports queuing, logging, undo/redo

* Easy to add new commands

* Useful in GUI buttons, macro recording, transaction systems

4. **(a)** Describe the Java Collection Framework: key interfaces and classes. (b) Compare `ArrayList`,
`LinkedList`, `HashSet`, `TreeSet`, `HashMap`, `TreeMap`. (c) When to choose which?

**(a)** The core interfaces are: `Collection`, `List`, `Set`, `Queue`, `Deque`, `Map` (though `Map` is
outside `Collection`). Key classes: `ArrayList`, `LinkedList`, `HashSet`, `LinkedHashSet`, `TreeSet`,
`PriorityQueue`, `HashMap`, `LinkedHashMap`, `TreeMap`. Utility classes: `Collections`, `Arrays`.

**(b)**
| Collection | Order / Behavior | Time complexities | Null / duplicates
| Notes |

| --------------- | ------------------------------------ | ------------------------------------------------ |


------------------------------------------------ | ------------------------------------------------ |

| `ArrayList` | Insertion order | get O(1), add O(1 amortized), insert/delete O(n) | allows
duplicates, many nulls | Good for random access and many reads |

| `LinkedList` | Insertion order | get O(n), add/remove at ends O(1) | allows


duplicates | Good when frequent insertions/removals in middle |

| `HashSet` | No order | add/contains/remove O(1) average | no


duplicates, allows one null | Backed by `HashMap` |

| `TreeSet` | Sorted order (natural or comparator) | O(log n) for add/contains/remove |


no duplicates, no null (if comparator prohibits) | Good when sorted order needed |

| `HashMap` | No key order | put/get/remove O(1) average | allows one


null key, many null values | Key-value mapping |

| `TreeMap` | Sorted key order | O(log n) | no null keys


(depending on comparator) | Useful when keys must be in sorted order |

| **(c)** Choose: | | | |
|

* `ArrayList` when you need fast random access

* `LinkedList` when many insertions/removals (especially at middle or ends)

* `HashSet` when uniqueness is required and order doesn’t matter

* `TreeSet` when you need sorted unique elements

* `HashMap` for general key-value mapping without ordering

* `TreeMap` when you need sorted keys in your map

5. **(a)** Explain how `HashMap` works internally (b) What is the difference between fail-fast and fail-
safe iterators in Java Collections?
**(a)**

* `HashMap` uses an array of buckets (Node[]). Each bucket holds a linked list (or tree for many
entries) of `Node` entries.

* To insert: compute `hashCode()`, map to bucket index, then if collision, traverse list/tree; if key
exists, replace value; else add new node.

* For performance, when chain length exceeds threshold (e.g. 8), it converts to a balanced tree
(Red-Black tree).

* On rehash (when load factor threshold exceeded), double the bucket array size and re-distribute
entries.

* `get(key)` computes hash, finds bucket, then traverses to match key via equals.

**(b)**

* **Fail-fast:** Iterator detects concurrent modification (via `modCount`) and throws


`ConcurrentModificationException` if collection is modified during iteration (except via iterator’s own
`remove`). Most standard Collections (ArrayList, HashMap, etc.) provide fail-fast iterators.

* **Fail-safe:** The iterator works on a clone or snapshot of the data. It doesn’t throw exception
when the collection is modified, but changes may not be reflected in iteration. Example:
`CopyOnWriteArrayList

You might also like