0% found this document useful (0 votes)
3 views16 pages

COS202 Study Guide

The COS202 Study Guide covers advanced object-oriented programming concepts, data structures, and algorithms, including polymorphism, abstract classes, and various data structures like stacks and queues. It provides key points, definitions, and comparisons between concepts, along with a set of 40 multiple-choice questions to test understanding. The guide emphasizes the importance of using appropriate data structures and algorithms for efficient programming.

Uploaded by

adekeyeolaoluwa9
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)
3 views16 pages

COS202 Study Guide

The COS202 Study Guide covers advanced object-oriented programming concepts, data structures, and algorithms, including polymorphism, abstract classes, and various data structures like stacks and queues. It provides key points, definitions, and comparisons between concepts, along with a set of 40 multiple-choice questions to test understanding. The guide emphasizes the importance of using appropriate data structures and algorithms for efficient programming.

Uploaded by

adekeyeolaoluwa9
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

COS202 – Advanced OOP & Data

Structures
Comprehensive Study Guide
Key Points • Summary Tables • 40 Objective Questions with Answers

COS202 – Study Guide | Page 1


MODULE 1: Advanced Object-Oriented Programming

1. Polymorphism
Polymorphism means 'many forms.' It is the ability to treat objects of different concrete classes
through a common reference type and still obtain behaviour specific to the actual object at
runtime.

Key Idea
Polymorphism eliminates repetitive if-else type-checking. The program sends a single
message (e.g. calculateBonus()) and the correct subclass implementation runs
automatically — this is called dynamic method dispatch.

Key Points:
• The most common form is subtype polymorphism — a base class or interface reference
can point to any compatible subclass object.
• Declared type vs. actual type: e.g. Employee e1 = new Lecturer(...) — declared as
Employee, actual object is Lecturer.
• Method calls are resolved at runtime based on the actual object, not the reference type.
• Reduces coupling and makes code more flexible and extensible.

2. Abstract Classes vs. Interfaces

Construct Can Contain Instantiable? Typical Use


Implementation?
Concrete Class Yes Yes Create and use objects directly
Abstract Class Yes (partial) No Shared state/behaviour for related
subclasses
Interface No state; default No Behavioural contract across
methods only (Java unrelated classes
8+)

Key Points:
• Use an abstract class when classes share an 'is-a' relationship and common
implementation code.
• Use an interface when you need a capability contract that unrelated classes can fulfil
(e.g. Printable, Exportable, Comparable).

COS202 – Study Guide | Page 2


• A class can implement multiple interfaces but can extend only one abstract class (in
Java/C#).
• An abstract class can contain constructors, fields, and both abstract and concrete
methods.

3. Class Hierarchies
Key Points:
• A class hierarchy organises types from general (top) to specific (bottom).
• Common data (e.g. name, id) and shared methods live in the base class to avoid
duplication.
• Specialised methods (e.g. calculateBonus(), registerCourse()) are placed in subclasses.
• Avoid forcing unrelated classes into the same hierarchy — prefer composition over
inheritance when there is no clear 'is-a' relationship.
• Example hierarchy: Person → Student / Staff → Lecturer / Administrator

4. Packages and Namespaces


Key Points:
• Java uses packages; C# uses namespaces — both serve the same purpose: organise
code logically.
• Benefits: prevent name clashes, improve readability, signal architectural intent, support
team collaboration.
• A package or namespace should reflect cohesive responsibility (e.g. models, services,
ui).
• Declaration example (Java): package [Link];
• Poor practice: placing all classes in one global scope.

5. Collections API — Iterator, List, Stack, Queue


Modern languages provide tested, efficient data structures. Use the API instead of writing
custom containers.

API Type Ordering Rule Core Operations Example Use Case


List Indexed / positional add, get, set, remove, Class register, transaction history
iterate
Stack LIFO – Last In, push, pop, peek Undo operations, expression
First Out evaluation, backtracking
Queue FIFO – First In, offer/enqueue, Print jobs, task scheduling,
First Out poll/dequeue, peek customer queues
Iterator Sequential hasNext(), next() Safe traversal of any Collection
traversal

COS202 – Study Guide | Page 3


API Type Ordering Rule Core Operations Example Use Case
Enumeration Sequential hasMoreElements(), Older classes like Vector
(legacy) traversal nextElement()

Iterator vs. Enumeration


Iterator is the modern standard and integrates with the Collections Framework. Enumeration
is legacy (used with Vector). Iterator also supports safe element removal during iteration;
Enumeration does not.

COS202 – Study Guide | Page 4


MODULE 2: Data Structures and Algorithms

6. Searching Algorithms

Method Data Requirement Time Complexity When to Use


Linear Search None – works on sorted or O(n) worst case Small datasets or
unsorted data unsorted data
Binary Search Data MUST be sorted first O(log n) worst case Large sorted datasets
with repeated searches

Key Points:
• Linear search checks each element one by one from the start.
• Binary search compares the target with the middle element, then halves the search
space.
• Binary search is far more efficient for large datasets but requires a sorted array.
• Important principle: a faster algorithm may require stronger preconditions.

7. Sorting Algorithms

Algorithm Core Idea Worst-Case Notable Property


Time
Bubble Sort Swap adjacent out-of-order O(n²) Easiest to understand;
values repeatedly inefficient for large data
Selection Sort Find the smallest remaining O(n²) Fewer swaps than Bubble
item and place it Sort
Insertion Sort Insert each item into its O(n²) Efficient for small or
correct position in a sorted nearly sorted data
prefix
API Sort Library-managed (Timsort in O(n log n) Best choice for production
([Link] / Java) code
[Link])

8. Recursive Algorithms

Definition

COS202 – Study Guide | Page 5


Recursion is a method that calls itself to solve a smaller version of the same problem. Every
recursive solution must have: (1) a Base Case — stops the recursion, and (2) a Recursive
Case — reduces the problem toward the base case.

Key Points:
• Each recursive call is stored on the program stack; when the base case is reached, calls
return in reverse order.
• Recursion is natural for divide-and-conquer problems, trees, and nested structures.
• Missing or wrong base case → infinite recursion → stack overflow (runtime crash).
• Factorial example: factorial(n) = n × factorial(n-1), with factorial(0) = factorial(1) = 1.
• Recursive binary search: each call passes a narrowed [low, high] range until the target is
found or low > high.
• Trade-off: recursion is elegant but uses more memory per call than an equivalent
iterative solution.

COS202 – Study Guide | Page 6


Quick Reference: Key Distinctions to Remember

Topic Remember This


Polymorphism Same reference type, different runtime behaviour — resolved by the
JVM at execution time.
Abstract class vs Interface Abstract class = shared code + is-a. Interface = capability contract,
multiple allowed.
Stack vs Queue Stack = LIFO (last in, first out). Queue = FIFO (first in, first out).
Iterator vs Enumeration Iterator is modern (Collections Framework). Enumeration is legacy
(Vector).
Linear vs Binary Search Linear = O(n), no sorting needed. Binary = O(log n), requires sorted
data.
Recursion requirements Must have a base case AND a recursive case that reduces toward
the base case.
Package/Namespace Reflects responsibility, not convenience. Prevents name clashes and
improves modularity.

COS202 – Study Guide | Page 7


Objective Questions (40 MCQs) with Answers
Instructions: For each question, select the best answer from the options provided. Answers and
explanations follow each question.

Section A – Advanced OOP (Questions 1–20)

Q1. What does polymorphism literally mean?


A) Single form
B) Multiple inheritance
C) Many forms
D) Abstract behaviour
✔ Answer: C) Many forms
Explanation: Polymorphism comes from the Greek words 'poly' (many) and 'morph' (form), meaning an
entity can take many forms.

Q2. Which of the following best describes runtime polymorphism in Java?


A) A method is resolved at compile time based on the declared type
B) A method is resolved at runtime based on the actual object type
C) A method cannot be overridden in subclasses
D) Interfaces are used to prevent method overriding
✔ Answer: B) A method is resolved at runtime based on the actual object type
Explanation: Dynamic method dispatch selects the correct overridden method at runtime according to
the actual (concrete) class of the object.

Q3. Which keyword is used in Java to indicate that a class cannot be instantiated directly?
A) static
B) final
C) abstract
D) private
✔ Answer: C) abstract
Explanation: The 'abstract' keyword marks a class as incomplete and prevents direct instantiation; it
must be subclassed.

Q4. What is the key difference between an abstract class and an interface?
A) An interface can have constructors; an abstract class cannot
B) An abstract class can contain implementation code; a classic interface cannot
C) An interface enforces LIFO behaviour
D) An abstract class cannot have any methods
✔ Answer: B) An abstract class can contain implementation code; a classic interface cannot
Explanation: Abstract classes can hold fields, constructors, and fully implemented methods. Traditional
interfaces only declare method signatures (no state).

Q5. A class that implements an interface MUST:

COS202 – Study Guide | Page 8


A) Extend another class
B) Provide implementations for all interface methods (unless it is abstract itself)
C) Declare all fields as private
D) Override toString()
✔ Answer: B) Provide implementations for all interface methods (unless it is abstract itself)
Explanation: Any concrete class implementing an interface is obligated to implement every method
declared in that interface.

Q6. In a class hierarchy, where should shared data such as 'name' and 'id' typically be placed?
A) In every subclass separately
B) In the base (parent) class
C) In an interface
D) In the main method only
✔ Answer: B) In the base (parent) class
Explanation: Placing common data in the base class avoids code duplication and allows all subclasses
to inherit it.

Q7. Which of the following is an example of a good reason to use inheritance?


A) Two classes share the same variable name
B) A Lecturer 'is-a' type of Employee
C) Two classes are in the same package
D) A class needs to use a List
✔ Answer: B) A Lecturer 'is-a' type of Employee
Explanation: Inheritance should model a genuine 'is-a' relationship. Lecturer is a specialisation of
Employee, making inheritance appropriate.

Q8. In Java, a package declaration must appear:


A) After all import statements
B) At the very beginning of the source file, before imports
C) Inside the class body
D) After the class declaration
✔ Answer: B) At the very beginning of the source file, before imports
Explanation: The package statement must be the first line of code (excluding comments) in a Java
source file.

Q9. Which collection type uses LIFO ordering?


A) Queue
B) List
C) Stack
D) Iterator
✔ Answer: C) Stack
Explanation: A Stack removes the most recently added element first — Last In, First Out (LIFO).

Q10. Which collection type uses FIFO ordering?


A) Stack
B) Queue
C) ArrayList
D) LinkedList (as a stack)

COS202 – Study Guide | Page 9


✔ Answer: B) Queue
Explanation: A Queue processes elements in the order they were added — First In, First Out (FIFO).

Q11. Which method is used to remove and return the front element of a Java Queue?
A) pop()
B) peek()
C) poll()
D) dequeue()
✔ Answer: C) poll()
Explanation: [Link]() removes and returns the head (front) element of the queue. peek() reads it
without removing.

Q12. Which traversal mechanism is the modern Java standard for iterating collections?
A) Enumeration
B) Iterator
C) for loop only
D) while loop only
✔ Answer: B) Iterator
Explanation: Iterator integrates with the Java Collections Framework and supports hasNext(), next(), and
safe removal.

Q13. What does the Iterator method hasNext() return?


A) The next element in the collection
B) True if there are more elements to visit, false otherwise
C) The index of the current element
D) The size of the collection
✔ Answer: B) True if there are more elements to visit, false otherwise
Explanation: hasNext() is a boolean check used before calling next() to avoid a
NoSuchElementException.

Q14. The Enumeration interface uses which method to retrieve the next element?
A) next()
B) getNext()
C) nextElement()
D) fetchNext()
✔ Answer: C) nextElement()
Explanation: Enumeration uses hasMoreElements() and nextElement(), as opposed to Iterator's
hasNext() and next().

Q15. Which Java data structure is most suitable for implementing an 'undo' feature?
A) Queue
B) List
C) Stack
D) Set
✔ Answer: C) Stack
Explanation: Undo operations require reversing the most recent action first — exactly the LIFO
behaviour of a Stack.

Q16. When should you prefer an interface over an abstract class?

COS202 – Study Guide | Page 10


A) When related classes need to share common fields
B) When unrelated classes need to fulfil a common behavioural contract
C) When you need a constructor in the base type
D) When only one class will implement the behaviour
✔ Answer: B) When unrelated classes need to fulfil a common behavioural contract
Explanation: Interfaces express capability contracts that can be applied to completely unrelated classes
(e.g. Report and Transcript both implementing Exportable).

Q17. Which of the following is NOT a valid benefit of using packages/namespaces?


A) Prevent name clashes
B) Signal architectural intent
C) Automatically increase program speed
D) Improve readability and modularity
✔ Answer: C) Automatically increase program speed
Explanation: Packages and namespaces are an organisational tool. They do not affect execution speed.

Q18. What problem does polymorphism solve that repeated if-else checking does not solve
elegantly?
A) It makes code shorter by removing all conditionals
B) It allows one reference type to invoke type-specific behaviour without manual branching
C) It makes all methods run faster
D) It prevents subclasses from overriding methods
✔ Answer: B) It allows one reference type to invoke type-specific behaviour without manual
branching
Explanation: Polymorphism replaces chains of if-else or switch-type checks with dynamic dispatch,
making code cleaner and easier to extend.

Q19. Which of the following pairs is correctly matched?


A) Stack – FIFO, Queue – LIFO
B) Stack – LIFO, Queue – FIFO
C) List – LIFO, Stack – FIFO
D) Queue – indexed access, List – FIFO
✔ Answer: B) Stack – LIFO, Queue – FIFO
Explanation: Stack follows Last In First Out; Queue follows First In First Out. This is a fundamental
distinction.

Q20. In Java, how many interfaces can a single class implement?


A) Only one
B) At most two
C) Unlimited (multiple interfaces allowed)
D) None — only abstract classes can implement interfaces
✔ Answer: C) Unlimited (multiple interfaces allowed)
Explanation: Java allows a class to implement any number of interfaces simultaneously, enabling
flexible multiple-capability design.

COS202 – Study Guide | Page 11


Section B – Data Structures and Algorithms (Questions 21–40)

Q21. What is the time complexity of linear search in the worst case?
A) O(1)
B) O(log n)
C) O(n)
D) O(n²)
✔ Answer: C) O(n)
Explanation: In the worst case, linear search checks every element, so it performs n comparisons for n
elements.

Q22. Binary search has a time complexity of:


A) O(n)
B) O(n²)
C) O(log n)
D) O(1)
✔ Answer: C) O(log n)
Explanation: Binary search halves the search space on each step, producing a logarithmic number of
comparisons.

Q23. What precondition is required before applying binary search?


A) The array must contain only integers
B) The array must be sorted
C) The array must have an odd number of elements
D) The array must be stored in a Stack
✔ Answer: B) The array must be sorted
Explanation: Binary search relies on the sorted order to decide which half to continue searching. It will
not work correctly on unsorted data.

Q24. In binary search, after comparing the target with the middle element and finding the target
is larger, what happens next?
A) The search ends with failure
B) The left half is searched
C) The right half is searched
D) The entire array is rescanned
✔ Answer: C) The right half is searched
Explanation: If target > middle element, the target must be in the right half (higher values), so low is set
to mid + 1.

Q25. Which sorting algorithm repeatedly compares and swaps adjacent elements?
A) Insertion Sort
B) Selection Sort
C) Bubble Sort
D) Merge Sort
✔ Answer: C) Bubble Sort
Explanation: Bubble Sort passes through the array swapping out-of-order adjacent pairs until the array is
sorted.

COS202 – Study Guide | Page 12


Q26. Selection Sort works by:
A) Inserting each element into its correct position in a sorted prefix
B) Finding the smallest remaining element and placing it in its correct position
C) Swapping adjacent elements repeatedly
D) Dividing the array into halves and merging
✔ Answer: B) Finding the smallest remaining element and placing it in its correct position
Explanation: Selection Sort selects the minimum from the unsorted portion and swaps it to the end of the
sorted portion on each pass.

Q27. Which sorting algorithm is most efficient for small or nearly sorted datasets?
A) Bubble Sort
B) Selection Sort
C) Insertion Sort
D) They all perform identically
✔ Answer: C) Insertion Sort
Explanation: Insertion Sort has near O(n) performance on nearly sorted data because very few shifts are
needed.

Q28. What is the worst-case time complexity of Bubble, Selection, and Insertion Sort?
A) O(n)
B) O(log n)
C) O(n log n)
D) O(n²)
✔ Answer: D) O(n²)
Explanation: All three elementary sorting algorithms have quadratic worst-case time complexity, making
them unsuitable for very large datasets.

Q29. Which Java API method sorts an ArrayList?


A) [Link](list)
B) [Link](list)
C) [Link]()
D) [Link](list)
✔ Answer: B) [Link](list)
Explanation: [Link]() is the standard Java API method for sorting List implementations such as
ArrayList.

Q30. What are the two essential components every recursive method must contain?
A) A loop and a return statement
B) A base case and a recursive case
C) A constructor and a destructor
D) An interface and an abstract class
✔ Answer: B) A base case and a recursive case
Explanation: The base case stops further calls; the recursive case reduces the problem toward that base
case.

Q31. What happens if a recursive method has no base case?


A) It returns zero by default
B) It runs exactly once

COS202 – Study Guide | Page 13


C) It causes infinite recursion and eventually a stack overflow
D) It prints an error and stops cleanly
✔ Answer: C) It causes infinite recursion and eventually a stack overflow
Explanation: Without a base case, calls keep stacking until the JVM runs out of stack memory and
throws a StackOverflowError.

Q32. The factorial of 0 is defined as:


A) 0
B) 1
C) Undefined
D) -1
✔ Answer: B) 1
Explanation: By mathematical convention, 0! = 1. This serves as the base case for the recursive factorial
algorithm.

Q33. Which data structure models the behaviour of recursive method calls internally?
A) Queue
B) List
C) Stack
D) Tree
✔ Answer: C) Stack
Explanation: Each recursive call is pushed onto the program call stack and popped when it returns —
exactly LIFO behaviour.

Q34. In the recursive binary search, what is the base case?


A) When the middle element equals the target
B) When low > high (search space exhausted)
C) Both A and B are correct base cases
D) When the array is empty only
✔ Answer: C) Both A and B are correct base cases
Explanation: Recursive binary search returns the index when target is found (A), or -1 when low > high
meaning the target is not present (B).

Q35. Which of the following is a disadvantage of recursion compared to iteration?


A) Recursion cannot solve binary search problems
B) Recursion uses more memory per call due to the call stack
C) Recursion cannot express factorial
D) Recursion always runs slower regardless of problem size
✔ Answer: B) Recursion uses more memory per call due to the call stack
Explanation: Every recursive call occupies a stack frame. Deep recursion on large inputs can exhaust
stack memory, unlike iterative solutions.

Q36. Which Java collection class is the older, legacy alternative to ArrayList?
A) Stack
B) Queue
C) Vector
D) LinkedList
✔ Answer: C) Vector

COS202 – Study Guide | Page 14


Explanation: Vector is a legacy class that predates the Collections Framework. Enumeration is used to
traverse it, unlike ArrayList which uses Iterator.

Q37. What does [Link]() use internally in modern Java?


A) Bubble Sort
B) Selection Sort
C) Dual-Pivot Quicksort (primitives) / Timsort (objects)
D) Linear Search
✔ Answer: C) Dual-Pivot Quicksort (primitives) / Timsort (objects)
Explanation: Java's [Link]() is highly optimised — it uses Dual-Pivot Quicksort for primitive arrays
and Timsort for object arrays, both far more efficient than O(n²) sorts.

Q38. A Queue is most suitable for which of the following scenarios?


A) Reversing a string
B) Evaluating arithmetic expressions
C) Managing print job order (first submitted, first printed)
D) Implementing an undo feature
✔ Answer: C) Managing print job order (first submitted, first printed)
Explanation: Print jobs are processed in the order they arrive — FIFO — which is exactly what a Queue
provides.

Q39. In Java, which interface does LinkedList implement that makes it usable as a Queue?
A) List only
B) Stack
C) Queue
D) Iterator
✔ Answer: C) Queue
Explanation: LinkedList implements both List and Queue interfaces, so it can be used as a FIFO queue
using offer(), poll(), and peek().

Q40. Which statement about the Java Collections Framework is FALSE?


A) ArrayList provides efficient random access by index
B) LinkedList is efficient for frequent insertions at known positions
C) Iterator integrates with the Collections Framework and supports element removal
D) Stack is the recommended modern implementation for queue-like behaviour
✔ Answer: D) Stack is the recommended modern implementation for queue-like behaviour
Explanation: Stack provides LIFO (not queue) behaviour. For queue-like FIFO operations, use Queue
implemented by LinkedList or ArrayDeque.

COS202 – Study Guide | Page 15


Answer Key (Quick Reference)

Q Answer Q Answer Q Answer Q Answer


1 C 11 C 21 C 31 C
2 B 12 B 22 C 32 B
3 C 13 B 23 B 33 C
4 B 14 C 24 C 34 C
5 B 15 C 25 C 35 B
6 B 16 B 26 B 36 C
7 B 17 C 27 C 37 C
8 B 18 B 28 D 38 C
9 C 19 B 29 B 39 C
10 B 20 C 30 B 40 D

End of Study Guide

COS202 – Study Guide | Page 16

You might also like