An original Thinka practice paper modelled on the structure and difficulty of the Nov 2024 HL IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.
Paper 1 Section A
Answer all questions. Short-answer questions testing core syllabus knowledge.
10 PastPaper.question · 25 PastPaper.marks
PastPaper.question 1 · Short Answer
2.5 PastPaper.marks
Define the term 'usability' and outline one reason why it is crucial in the design of a digital medical records system.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Usability refers to how effectively, efficiently, and satisfactorily a user can interact with a software system to achieve their goals. In the context of a digital medical records system, medical staff need to input and retrieve critical patient data quickly and accurately. Poor usability can lead to slower retrieval times or input errors, which in emergency clinical situations could result in incorrect treatments or compromised patient safety.
PastPaper.markingScheme
[1 mark] For a complete definition of usability (efficiency, effectiveness, and user satisfaction within a specific context of use). [1.5 marks] For a detailed explanation of why it is crucial in a medical records system: 1 mark for linking usability to speed/accuracy of data entry or retrieval, and 0.5 marks for connecting this directly to medical outcomes (e.g., patient safety, emergency response, avoiding clinical errors).
PastPaper.question 2 · Short Answer
2.5 PastPaper.marks
Explain the role of a routing table in packet-switching networks.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A routing table is a database stored in a router that lists the routes to particular network destinations, along with metrics associated with those routes. When a packet arrives, the router reads the destination IP address, consults its routing table to find the best match (often the longest prefix match), and forwards the packet to the next hop or interface. This enables dynamic and efficient path selection across decentralized networks.
PastPaper.markingScheme
[1 mark] For identifying that a routing table stores a list of network destinations and paths. [1 mark] For explaining that the router uses it to determine the next hop or interface for an incoming packet based on its destination address. [0.5 marks] For noting that routing tables can be dynamically updated using routing protocols to optimize traffic flow.
PastPaper.question 3 · Short Answer
2.5 PastPaper.marks
Describe the relationship between the CPU, cache memory, and primary memory (RAM) during a read operation.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
During a read operation, the CPU first checks the high-speed cache memory for the required instructions or data. If the data is present (a cache hit), the CPU reads it immediately, minimizing latency. If the data is not in the cache (a cache miss), the CPU must access the slower primary memory (RAM) to fetch the data. This data is then loaded into the CPU registers and simultaneously copied into the cache to speed up subsequent accesses.
PastPaper.markingScheme
[1 mark] For stating that the CPU checks cache memory first before attempting to access RAM. [1 mark] For describing the difference between a cache hit (instant read from cache) and a cache miss (fetch from RAM and copy to cache). [0.5 marks] For identifying that cache is much faster than RAM, thereby minimizing CPU idle time/latency.
PastPaper.question 4 · Short Answer
2.5 PastPaper.marks
Explain why a recursive algorithm must have a base case, and state the consequence if it is missing or never reached.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A recursive function calls itself to solve smaller sub-problems. The base case is a simple, non-recursive condition that returns a direct value, acting as the terminating condition for the recursion. If a base case is missing or the input never satisfies the base case condition, the function will execute infinite recursion. This leads to the call stack filling up completely, resulting in a 'stack overflow' error and terminating the program due to memory exhaustion.
PastPaper.markingScheme
[1 mark] For explaining the role of the base case as the terminating condition that stops the recursive loop. [1.5 marks] For describing the consequence: 1 mark for identifying that it causes infinite recursion/stack overflow, and 0.5 marks for explaining that this occurs due to exhausting the memory/call stack space.
PastPaper.question 5 · Short Answer
2.5 PastPaper.marks
Distinguish between a static data structure and a dynamic data structure, referencing memory allocation in your answer.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A static data structure has a fixed, predetermined size allocated in memory at compile-time or upon initialization (e.g., a standard array). Once created, its size cannot be changed. In contrast, a dynamic data structure can adjust its size during program execution (runtime), growing or shrinking to accommodate data (e.g., a linked list). It dynamically allocates or deallocates memory using pointers or references as elements are added or removed.
PastPaper.markingScheme
[1 mark] For explaining that static data structures have a fixed size determined at compile-time/initialization and cannot change. [1 mark] For explaining that dynamic data structures can grow/shrink at runtime, allocating/deallocating memory dynamically. [0.5 marks] For providing a clear comparative example of each (e.g., array vs linked list).
PastPaper.question 6 · Short Answer
2.5 PastPaper.marks
Define the OOP concept of 'encapsulation' and outline one benefit it provides during software maintenance.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Encapsulation is an OOP principle where the data (attributes) and the code (methods) that manipulate that data are bundled together into a single unit (a class), with access to the internal state restricted using private/protected access modifiers. During software maintenance, encapsulation provides the benefit of information hiding. Developers can safely modify the internal implementation details of a class without affecting any external classes that interact with it, minimizing bugs and system-wide ripple effects.
PastPaper.markingScheme
[1 mark] For a correct definition of encapsulation (bundling data and methods, and restricting access using access modifiers). [1.5 marks] For explaining the maintenance benefit: 1 mark for explaining that it isolates or localizes changes within the class, and 0.5 marks for pointing out that it prevents external dependencies from breaking/unintended side effects.
PastPaper.question 7 · Short Answer
2.5 PastPaper.marks
In the context of an automated home heating system, describe the role of a closed-loop feedback system.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
In an automated home heating system, a closed-loop feedback system continuously regulates the room temperature. A temperature sensor (the feedback mechanism) measures the current ambient temperature and sends this data back to the central controller. The controller compares this actual input against the desired target temperature (setpoint). If the temperature is too low, the controller signals the heating element (actuator) to turn on; once the target is reached, it signals it to turn off. This continuous cycle maintains a stable state without human intervention.
PastPaper.markingScheme
[1 mark] For describing how sensors measure the actual output (ambient temperature) and feed it back to the controller. [1 mark] For explaining how the controller compares this feedback to a setpoint and commands the actuator (heater) to adjust. [0.5 marks] For highlighting that this creates a continuous, automated control loop to maintain stable room conditions.
PastPaper.question 8 · Short Answer
2.5 PastPaper.marks
State the pre-condition necessary for a binary search to be performed on an array, and explain why a binary search is significantly more efficient than a linear search for large datasets.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The essential pre-condition for running a binary search is that the array must be sorted in ascending or descending order. Binary search is far more efficient than linear search for large datasets because of its logarithmic time complexity, \(O(\log n)\). Instead of checking elements one by one from start to finish like linear search (\(O(n)\)), binary search compares the target to the middle element and halves the remaining search space with each iteration. For large arrays, this dramatically reduces the number of comparisons required to find the element or determine its absence.
PastPaper.markingScheme
[1 mark] For stating that the array must be sorted. [1.5 marks] For explaining the efficiency: 1 mark for explaining that binary search halves the remaining search space at each step compared to linear search's sequential checks, and 0.5 marks for referencing the respective time complexities, \(O(\log n)\) vs \(O(n)\).
PastPaper.question 9 · Short Answer
2 PastPaper.marks
Identify two potential compatibility issues that may arise when migrating data from a legacy database system to a newly developed system.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
When migrating data from a legacy system to a new system, compatibility issues often occur due to: 1. Schema differences: The tables, fields, or relationship constraints in the legacy database might not align with the new database's design (e.g., differing date formats or text field lengths). 2. Character encoding: The legacy system might use a different character encoding scheme (like ASCII or a localized standard) compared to the new system (which may use UTF-8/Unicode), causing data corruption or loss of special characters.
PastPaper.markingScheme
Award [1] mark for each valid compatibility issue identified, up to a maximum of [2] marks. Valid answers include: Differences in database schema/structure/data types; Incompatible character encoding (e.g., ASCII vs UTF-8); Differing validation rules or constraints; Scale/precision differences in numeric fields.
PastPaper.question 10 · Short Answer
3 PastPaper.marks
Explain the role of the Program Counter (PC) and its relationship with the Memory Address Register (MAR) during the fetch stage of the machine instruction cycle.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
During the fetch stage of the machine instruction cycle, the Program Counter (PC) stores the memory address of the next instruction to be executed. To begin the fetch process, this address is copied from the PC to the Memory Address Register (MAR), which directly interfaces with the address bus to locate the instruction in RAM. Once the address is copied, the PC is incremented by one so that it points to the subsequent instruction for the next cycle.
PastPaper.markingScheme
Award [1] mark for explaining that the PC holds the address of the next instruction to be fetched/executed. Award [1] mark for stating that this address is copied to the MAR (to locate/access the instruction in RAM). Award [1] mark for stating that the PC is then incremented to point to the next instruction in sequence.
Paper 1 Section B
Answer all questions. Scenario-based structured and algorithmic questions.
5 PastPaper.question · 75 PastPaper.marks
PastPaper.question 1 · Structured
15 PastPaper.marks
A university library reservation system is designed using object-oriented principles. The system includes two classes: Book and Member. A Member can reserve up to 5 books at any given time.
The class Book has the following private attributes and methods: - ISBN (String) - title (String) - isReserved (Boolean) - Constructor Book(String isbn, String title) - Getters for all attributes, and a setter setReserved(Boolean reserved)
The class Member has the following attributes: - memberID (String) - name (String) - reservations (Array of 5 Book objects, initialized to null)
(a) Describe the relationship between the Member class and the Book class in this system, referring to aggregation or association. [2 marks]
(b) Outline one advantage of using private instance variables in the Book class combined with public getter and setter methods. [3 marks]
(c) Construct a pseudocode method addReservation(Book newBook) in the Member class. The method should: - Check if the book is already in the reservations array (to avoid duplicate reservations by matching its ISBN). - Check if there is an available slot (represented by null in the array). - If there is space and it is not a duplicate, add the book to the array, set the book's reservation status to true using its setter method, and return true. - Otherwise, return false. [6 marks]
(d) The library decides to introduce two new media types: Audiobook and EBook as subclasses of Book. Each subclass has a different rule for calculating the loan period: - Book has a standard duration of 14 days. - Audiobook has a duration of 21 days. - EBook has a duration of 7 days.
Explain how polymorphism can be applied in this scenario to calculate the correct loan duration for a collection of diverse media items without knowing their specific subclass at runtime. [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Aggregation or association represents a weak 'has-a' relationship. The life cycle of a Book is separate from the life cycle of a Member. Removing a Member from the system does not destroy the Book records associated with them. (b) Encapsulation ensures internal object states cannot be directly manipulated or set to invalid configurations from external classes. It localizes data management and allows implementation changes inside the Book class without breaking dependent code. (c) The solution iterates through the static reservations array of size 5. It safely checks for non-null items first to avoid NullPointerExceptions, compares the ISBN properties to detect duplicates, tracks the first empty index, and commits the reservation if conditions are satisfied. (d) The superclass Book defines a common interface: public int getLoanPeriod(). Subclasses override this method to provide specific loan durations. When client code iterates over a collection of Book objects and calls getLoanPeriod(), the system resolves the method call at runtime depending on the actual instance type (polymorphism).
PastPaper.markingScheme
(a) - 1 mark for identifying the relationship as aggregation or association. - 1 mark for explaining that the lifetime of the Book is independent of the Member.
(b) - 1 mark for mentioning encapsulation / data hiding. - 1 mark for explaining that this prevents direct unauthorized access/modification. - 1 mark for noting that it allows the internal implementation to change without affecting external code (or allows validation).
(c) - 1 mark for initializing boolean flag for duplicate and index pointer for empty space. - 1 mark for a correct loop iterating through the array (0 to 4). - 1 mark for correctly checking if an array element is not null and comparing ISBNs using getter. - 1 mark for identifying the first empty slot (checking for null and tracking index). - 1 mark for preventing additions if there is a duplicate or if the array is full. - 1 mark for assigning the book to the empty slot, calling setReserved(true), and returning the correct boolean values.
(d) - 1 mark for explaining that the parent class Book defines a method (e.g., getLoanPeriod()). - 1 mark for explaining that the subclasses (Audiobook, EBook) override this method with their specific behavior. - 1 mark for explaining that a collection (array) of type Book can hold instances of any subclass. - 1 mark for stating that at runtime, the JVM/runtime environment dynamically binds the method call to the correct subclass implementation (dynamic binding).
PastPaper.question 2 · Structured
15 PastPaper.marks
A queue is an abstract data structure that can be implemented using either a static array or a dynamic linked list.
(a) Compare a static array implementation of a queue with a dynamic linked list implementation. Refer specifically to memory allocation and the conditions under which a queue overflow can occur in each. [4 marks]
(b) A circular queue is implemented using a fixed-size array DATA of size 5 (indices 0 to 4). It uses two integer variables: head (the index of the first item) and tail (the index of the next available slot). The queue is empty when head == tail and full when \((tail + 1) % 5 == head\).
Initially, the queue is empty, with head = 0 and tail = 0.
Describe step-by-step the states of head, tail, and the elements in the DATA array after the following sequence of operations are performed: 1. Enqueue 'A' 2. Enqueue 'B' 3. Dequeue 4. Enqueue 'C' 5. Enqueue 'D' 6. Enqueue 'E'
For each operation, specify if it succeeds or if an overflow/underflow occurs. [6 marks]
(c) Standard queues operate on a First-In-First-Out (FIFO) basis. Contrast this with a Priority Queue, and explain one real-world computer science application where a Priority Queue is necessary instead of a standard queue. [5 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Static array implementation requires a fixed compile-time size, meaning memory overhead is constant, whereas dynamic linked lists dynamically grow/shrink at runtime, presenting variable memory usage and additional pointer storage overhead. Queue overflow for static arrays is predictable (size constraint), while for linked lists, it occurs only during out-of-memory errors. (b) Sequential tracing: 1. Enqueue 'A' -> DATA[0] = 'A', tail = (0+1)%5 = 1. 2. Enqueue 'B' -> DATA[1] = 'B', tail = (1+1)%5 = 2. 3. Dequeue -> head = (0+1)%5 = 1. DATA[0] is marked as empty. 4. Enqueue 'C' -> DATA[2] = 'C', tail = (2+1)%5 = 3. 5. Enqueue 'D' -> DATA[3] = 'D', tail = (3+1)%5 = 4. 6. Enqueue 'E' -> DATA[4] = 'E', tail = (4+1)%5 = 0. Queue is full. (c) A priority queue processes items out of order based on critical priorities. For example, in an OS scheduler, critical interactive tasks (such as mouse input or sound processing) are given a higher priority than file system writes, preventing the computer from freezing during heavy I/O workloads.
PastPaper.markingScheme
(a) - 1 mark for stating static array memory is allocated at compile-time/fixed size, while dynamic linked list allocation happens at runtime. - 1 mark for describing that static arrays use contiguous memory whereas dynamic linked lists use pointers to link non-contiguous memory nodes. - 1 mark for explaining that static array queues overflow when elements reach the array capacity. - 1 mark for explaining that dynamic linked list queues overflow only when overall system memory (heap) is fully exhausted.
(b) - 1 mark for Operation 1 (Enqueue 'A') resulting in head=0, tail=1, element placed at index 0. - 1 mark for Operation 2 (Enqueue 'B') resulting in head=0, tail=2, element placed at index 1. - 1 mark for Operation 3 (Dequeue) resulting in head=1, tail=2, removing 'A'. - 1 mark for Operations 4 & 5 resulting in head=1, tail=4, elements placed at indices 2 and 3. - 1 mark for Operation 6 succeeding with head=1, tail=0, elements placed at index 4, and indicating that all operations completed successfully without error. - 1 mark for explaining that the queue is now full because (tail+1)%5 == head (i.e., (0+1)%5 == 1).
(c) - 1 mark for standard queue definition (FIFO). - 1 mark for priority queue definition (elements dequeued based on priority value). - 1 mark for mentioning that elements of identical priority are processed FIFO. - 1 mark for identifying a valid application (e.g., CPU process scheduling, network router packet scheduling). - 1 mark for explaining why the priority queue is necessary in that specific application.
PastPaper.question 3 · Structured
15 PastPaper.marks
An algorithm is required to analyze temperature trends over a series of days. The program must find the length of the longest contiguous sub-array where the temperatures are strictly increasing.
For example, given the temperature array: TEMP = [15, 18, 11, 12, 14, 13, 16] The contiguous increasing sub-arrays are: - [15, 18] (length 2) - [11, 12, 14] (length 3) - [13, 16] (length 2) The longest is [11, 12, 14], so the algorithm should return 3.
(a) Construct an algorithm in pseudocode that accepts an integer array TEMP of size N (where \(N \ge 1\)) and returns the length of the longest strictly increasing contiguous sub-array. [7 marks]
(b) Trace your algorithm using the following array: TEMP = [12, 15, 14, 16, 17, 18, 15, 16] Clearly state the values of all variables used at each step of the iteration. [5 marks]
(c) State the Big O efficiency of your algorithm in terms of: (i) Time complexity. (ii) Space complexity. Justify your answers. [3 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) A single loop is sufficient for this task. It compares the current element with the previous one. If it is greater, the active run increases. Otherwise, the current run is evaluated against the max run, and the counter resets. A final comparison check is performed after the loop terminates. (b) Tracing is a step-by-step documentation of variable states. It demonstrates the correctness of logic when encountering resets (such as at index 2 and index 6). (c) The time complexity is linear \(O(N)\) since the loop executes exactly \(N-1\) times. The space complexity is constant \(O(1)\) because no auxiliary arrays or structures are allocated.
PastPaper.markingScheme
(a) - 1 mark for correct method signature and handling base case of empty array / single-element array. - 1 mark for initializing tracking variables (maxLength = 1, currentLength = 1). - 1 mark for correct loop from 1 to N-1 (or 0 to N-2). - 1 mark for correct comparison of adjacent elements (TEMP[i] > TEMP[i-1]). - 1 mark for incrementing currentLength when relation holds true. - 1 mark for correctly updating maxLength and resetting currentLength to 1 when relation fails. - 1 mark for checking currentLength > maxLength after loop ends and returning the result.
(b) - 1 mark for showing initial states correctly. - 1 mark for tracing steps up to i = 2 showing currentLength updates and then resetting with maxLength = 2. - 1 mark for tracing i = 3 to i = 5 showing currentLength increments up to 4. - 1 mark for tracing i = 6 showing maxLength updates to 4 and currentLength resets to 1. - 1 mark for tracing i = 7 and final return showing 4.
(c) - 1 mark for Time Complexity of \(O(N)\) with justification. - 1 mark for Space Complexity of \(O(1)\) with justification. - 1 mark for clear connection between algorithm mechanics and Big O notation.
PastPaper.question 4 · Structured
15 PastPaper.marks
A regional health authority plans to connect its local medical clinics to the main hospital database using a Virtual Private Network (VPN) over the public internet.
(a) Identify the OSI model layer at which the IPsec protocol primarily operates, and describe how IPsec uses packet encapsulation to ensure data confidentiality. [4 marks]
(b) Compare symmetric and asymmetric encryption. Explain why a VPN gateway utilizes both types of encryption during a secure remote session instead of relying on just one. [5 marks]
(c) In the context of a remote worker establishing a VPN connection from home: - State the purpose of a DHCP server. [2 marks] - Explain how the remote worker's laptop is assigned two separate IP addresses (one local to the home router, and one virtual address for the hospital LAN) during the process. [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) IPsec secures IP communications by encrypting and authenticating packets. In Tunnel Mode (encapsulation), the entire packet is encrypted and placed inside another packet. (b) A hybrid approach is used in TLS/IPsec. If only symmetric was used, sharing the key initially would be insecure. If only asymmetric was used, the encryption/decryption process would consume excessive CPU resources on the gateway. (c) The home router's DHCP handles local LAN routing to access the ISP. The corporate network's VPN server behaves as a secondary gateway, assigning a private nested IP to the client's virtual interface to direct internal packets.
PastPaper.markingScheme
(a) - 1 mark for identifying the Network Layer (Layer 3). - 1 mark for stating that the original IP packet (payload + original header) is encrypted. - 1 mark for stating that the encrypted packet is placed inside a new outer packet (capsule). - 1 mark for explaining that the new outer header conceals the original packet information from eavesdroppers.
(b) - 1 mark for defining symmetric encryption (same key, fast, suitable for data body). - 1 mark for defining asymmetric encryption (public/private key, slow, ideal for secure handshakes). - 1 mark for explaining asymmetric encryption is used during initial handshake/key negotiation. - 1 mark for explaining symmetric encryption is used for transmitting the actual body of data. - 1 mark for concluding that this provides both high security and performance.
(c) - 2 marks: 1 mark for automatic IP allocation, 1 mark for preventing manual configuration/conflicts. - 1 mark for stating the first IP address is assigned by the home network's DHCP server to the physical network card for local routing. - 1 mark for stating the second IP address is assigned by the remote network's system to a virtual network adapter. - 1 mark for explaining that the second IP is inside the target organization's subnet. - 1 mark for describing how traffic for the hospital is routed through the virtual adapter and encapsulated within packets sent from the physical adapter's IP address.
PastPaper.question 5 · Structured
15 PastPaper.marks
A school is migrating its student information system from a legacy, on-premise application to a modern cloud-based Software as a Service (SaaS) platform.
(a) Compare the "direct changeover" implementation method with the "phased implementation" method. For each method, identify one distinct advantage and one distinct disadvantage within the context of migrating sensitive student records. [6 marks]
(b) Data migration is a critical step in this system upgrade. Outline two compatibility issues that might arise when moving data from the legacy system to the new SaaS system. [4 marks]
(c) Explain the importance of user documentation for the school administrative staff, and describe two training methods that the school could use to ensure staff are comfortable with the new SaaS application. [5 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Direct implementation is fast but highly volatile, whereas phased implementation limits system exposure at the expense of prolonged transition periods. (b) Structural conflicts occur when old schemas don't match the new, structured SaaS databases (such as fields with different sizes or data types). File type differences occur when older database architectures run on distinct, legacy configurations. (c) User documentation offers reliable operational continuity. Workshops provide immediate interactive troubleshooting, while asynchronous video guides support various learning speeds.
PastPaper.markingScheme
(a) - 1 mark for defining direct changeover and 1 mark for defining phased implementation. - 1 mark for an advantage of direct changeover (e.g., swift, cheaper, no double-entry). - 1 mark for a disadvantage of direct changeover (e.g., high risk, no fallback if it fails). - 1 mark for an advantage of phased implementation (e.g., low risk, bugs isolated, gradual adaptation). - 1 mark for a disadvantage of phased implementation (e.g., long implementation time, complex data synchronization).
(b) - 1 mark for identifying compatibility issue 1 (e.g., character encoding/different file formats). - 1 mark for explaining why it occurs. - 1 mark for identifying compatibility issue 2 (e.g., database schema mismatch/field structural differences). - 1 mark for explaining why it occurs.
(c) - 1 mark for explaining the importance of user documentation (e.g., operational continuity, reference guide, reducing support calls). - 1 mark for identifying Training Method 1 (e.g., hands-on workshops). - 1 mark for explaining how Method 1 is effective. - 1 mark for identifying Training Method 2 (e.g., online video tutorials/e-learning modules). - 1 mark for explaining how Method 2 is effective.
Paper 2 Option D (OOP)
Answer all questions from this option. Core and extension object-oriented programming.
5 PastPaper.question · 65 PastPaper.marks
PastPaper.question 1 · Code Construction
13 PastPaper.marks
A climate monitoring system uses Object-Oriented Programming (OOP) to represent and manage different types of environmental sensors.
(a) Explain the concept of inheritance and how it supports code reusability in this scenario. [3 marks]
(b) Construct a Java class Sensor with the following requirements: - Private instance variables: id (String), location (String), and lastReading (double). - A constructor that initializes all three variables. - Getter methods for id and lastReading. - A method public boolean checkStatus() that returns true if lastReading is between 0.0 and 50.0 inclusive, otherwise false. [4 marks]
(c) Construct a subclass TemperatureSensor that extends Sensor: - Additional private instance variable: unit (String, e.g., 'C' or 'F'). - A constructor that takes four arguments (id, location, lastReading, unit) and correctly initializes them, utilizing the parent constructor. - An overridden checkStatus() method: If the unit is 'F', it converts the reading to Celsius first using the formula \( C = (F - 32) \times \frac{5}{9} \) before performing the range check (0.0 to 50.0 inclusive). Otherwise, it uses the inherited check. [6 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Part (a): Inheritance allows a new class (subclass) to inherit fields and methods from an existing class (superclass). In this scenario, common attributes like id, location, and lastReading, as well as behavior like standard status checking, are declared once in the superclass Sensor. The subclass TemperatureSensor automatically inherits these, eliminating redundant code while extending it with specific features (like unit handling).
Part (b): ```java public class Sensor { private String id; private String location; private double lastReading;
Part (a) [3 marks total]: - 1 mark: Define inheritance (subclass deriving properties/methods from superclass). - 1 mark: Explain how it eliminates code duplication / provides central maintenance. - 1 mark: Link specifically to the context (e.g., TemperatureSensor reuses Sensor's id/location/lastReading).
Part (b) [4 marks total]: - 1 mark: Correctly declaring private fields with matching data types. - 1 mark: Correct constructor initializing all three variables. - 1 mark: Valid implementation of getter methods (getId and getLastReading). - 1 mark: Correct boundary check in checkStatus() returning appropriate boolean.
Part (c) [6 marks total]: - 1 mark: Using the 'extends' keyword correctly in the class declaration. - 1 mark: Private instance variable 'unit' declared correctly. - 1 mark: Calling super(id, location, lastReading) inside subclass constructor. - 1 mark: Overriding checkStatus() method with identical signature. - 1 mark: Correctly calculating conversion from Fahrenheit to Celsius using formula. - 1 mark: Correct condition checking (utilizing super.checkStatus() or a matching manual comparison).
PastPaper.question 2 · Code Construction
13 PastPaper.marks
A software company manages payment processes using Object-Oriented principles.
(a) Distinguish between an abstract class and an interface, focusing on their usage and structures in Java. [3 marks]
(b) Construct the interface Payable containing a single abstract method calculatePay() which returns a double. Then, write the class Contractor that implements Payable: - Private instance variables: hourlyRate (double) and hoursWorked (int). - Constructor to initialize these variables. - Implement the calculatePay() method which returns the product of hourlyRate and hoursWorked. [5 marks]
(c) Write a static utility method, public static double calculateTotalPayout(Payable[] items), which accepts an array of Payable objects. The method must calculate and return the total sum of payments for all non-null objects in the array. If the array is null or empty, it should return 0.0. [5 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Part (a): An interface contains abstract behavior specifications (and constant static values) that multiple unrelated classes can implement, defining a formal contract. An abstract class is a conceptual base class that can contain implemented methods, instance variables, and constructors, and is intended to be a parent to closely related subclasses under a single hierarchy branch.
Part (b): ```java public interface Payable { double calculatePay(); }
public class Contractor implements Payable { private double hourlyRate; private int hoursWorked;
public Contractor(double hourlyRate, int hoursWorked) { this.hourlyRate = hourlyRate; this.hoursWorked = hoursWorked; }
Part (c): ```java public static double calculateTotalPayout(Payable[] items) { if (items == null || items.length == 0) { return 0.0; } double total = 0.0; for (int i = 0; i < items.length; i++) { if (items[i] != null) { total += items[i].calculatePay(); } } return total; } ```
PastPaper.markingScheme
Part (a) [3 marks total]: - 1 mark: Identifies interface containing only abstract method signatures (prior to Java 8 default methods). - 1 mark: Identifies abstract class able to have both concrete methods and instance states. - 1 mark: Mentions Java multi-inheritance limits (implements multiple interfaces, but extends only one class).
Part (b) [5 marks total]: - 1 mark: Interface definition with method double calculatePay(); - 1 mark: Contractor declaring implements Payable. - 1 mark: Correct private attributes in Contractor. - 1 mark: Constructor initializing fields. - 1 mark: Correct calculation and @Override of calculatePay().
Part (c) [5 marks total]: - 1 mark: Correct method signature (public static double calculateTotalPayout(Payable[])). - 1 mark: Check for overall array null/empty input returning 0.0. - 1 mark: Standard loop pattern iterating over items. - 1 mark: Guard checking individual element items[i] against null. - 1 mark: Accumulator adding elements using items[i].calculatePay() dynamically.
PastPaper.question 3 · Code Construction
13 PastPaper.marks
A flight reservation system utilizes class composition to represent passenger listings.
(a) Explain the difference between aggregation and composition using the relationship between Flight and Passenger objects as an illustrative example. [3 marks]
(b) Construct the class Passenger with: - Private instance variables: name (String), isFrequentFlyer (boolean), and classType (String, e.g., 'Economy', 'Business'). - Appropriate constructor. - Getter and setter methods for classType. - Getter method for isFrequentFlyer. [3 marks]
(c) Construct the class Flight with: - Private instance variables: flightNumber (String) and an array of Passenger objects named manifest. - A constructor that takes flightNumber and an array of Passenger objects to initialize the instance variables. - A method upgradeFrequentFlyers() which iterates through the entire manifest array. For every passenger who is a frequent flyer (isFrequentFlyer is true) and is currently in 'Economy', upgrade their classType to 'Business'. Guard against null elements in the array. [7 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Part (a): In composition, the lifetime of the child object is bound to the parent (a 'part-of' relationship). If Flight was destroyed, the passenger list would be destroyed if it were composition. Under aggregation (a 'has-a' relationship), the objects can exist independently. In real systems, a Passenger has an independent existence outside of any single Flight manifest, making aggregation more appropriate.
Part (b): ```java public class Passenger { private String name; private boolean isFrequentFlyer; private String classType;
public void upgradeFrequentFlyers() { if (this.manifest == null) { return; } for (int i = 0; i < this.manifest.length; i++) { if (this.manifest[i] != null) { if (this.manifest[i].getIsFrequentFlyer() && "Economy".equalsIgnoreCase(this.manifest[i].getClassType())) { this.manifest[i].setClassType("Business"); } } } } } ```
PastPaper.markingScheme
Part (a) [3 marks total]: - 1 mark: Clarifying aggregation (loose connection, independent lifecycle). - 1 mark: Clarifying composition (strong connection, co-dependent lifecycle). - 1 mark: Aligning correctly to context (e.g., Passenger persists if Flight cancelled = Aggregation).
Part (b) [3 marks total]: - 1 mark: Correct variables with private visibility modifiers. - 1 mark: Standard constructor mapping inputs correctly to state variables. - 1 mark: Full set of specified getters (getClassType, getIsFrequentFlyer) and setter (setClassType).
Part (c) [7 marks total]: - 1 mark: Flight class declaration with correct attribute types. - 1 mark: Constructor initializing attributes correctly. - 1 mark: upgradeFrequentFlyers method defined with correct signature. - 1 mark: Null-check on manifest array itself. - 1 mark: Iterating through manifest using length correctly. - 1 mark: Element safety check (manifest[i] != null) to prevent NullPointerException. - 1 mark: Correct conditional check (isFrequentFlyer and "Economy" comparison) leading to setClassType("Business").
PastPaper.question 4 · Code Construction
13 PastPaper.marks
A banking application manages client accounts while tracking performance metrics across all accounts.
(a) Outline the purpose and behavior of the static keyword when applied to class variables and methods in Java. [4 marks]
(b) Write the code for a BankAccount class containing: - Private instance variables: accountNumber (String) and balance (double). - A private static variable totalAccounts (int) initialized to 0. - A constructor that takes accountNumber and initial balance as parameters. It must increment totalAccounts each time an object is instantiated. - A public static getter method getTotalAccounts() that returns the value of totalAccounts. [5 marks]
(c) Write the method public void deposit(double amount) for the BankAccount class. This method must validate that amount is positive. If valid, update the balance. If invalid, throw an IllegalArgumentException with the message 'Deposit must be greater than zero'. [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Part (a): - Static variables are class-level variables shared among all instances of the class. Only one copy exists in memory. - Static methods are class-level methods that can be invoked without creating an instance of the class. They cannot directly access non-static variables or non-static methods.
Part (b): ```java public class BankAccount { private String accountNumber; private double balance; private static int totalAccounts = 0;
public static int getTotalAccounts() { return totalAccounts; } } ```
Part (c): ```java public void deposit(double amount) { if (amount <= 0.0) { throw new IllegalArgumentException("Deposit must be greater than zero"); } this.balance += amount; } ```
PastPaper.markingScheme
Part (a) [4 marks total]: - 1 mark: Static variables belong to the class rather than individual instances. - 1 mark: Only one copy of a static variable is shared among all instances. - 1 mark: Static methods can be called directly on the class (without instantiating objects). - 1 mark: Static methods cannot access non-static instance fields directly.
Part (b) [5 marks total]: - 1 mark: Accurate declaration of private instance fields. - 1 mark: Declaring private static int totalAccounts = 0; correctly. - 1 mark: Constructor initializing accountNumber and balance. - 1 mark: Incrementing totalAccounts inside constructor. - 1 mark: Writing public static int getTotalAccounts() with correct keyword placements.
Part (c) [4 marks total]: - 1 mark: Correct method signature (public void deposit(double amount)). - 1 mark: Logical check to detect zero or negative deposits (amount <= 0). - 1 mark: Raising dynamic IllegalArgumentException containing precise required string. - 1 mark: Safe and correct balance modification (this.balance += amount).
PastPaper.question 5 · Code Construction
13 PastPaper.marks
An inventory database manages library book objects using search algorithms.
(a) Explain the importance of encapsulation in designing a robust, maintainable class such as Book. [3 marks]
(b) Construct a class Book with: - Private instance variables: isbn (String), title (String), and price (double). - A constructor and getter methods for all three variables. [4 marks]
(c) Construct a search method in a controller class: public static int binarySearchBook(Book[] books, String targetIsbn). The array of books is already sorted alphabetically by isbn. The method must perform a standard binary search to find the index of the book matching targetIsbn. If the book is found, return its index. If it is not present in the array, return -1. Handle potential null references inside safety checks. [6 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Part (a): Encapsulation hides the internal details of a class from outside interference (using private attributes). Access is controlled through public methods (getters/setters). This prevents unauthorized state modification (e.g., negative book prices) and decouples class implementation from external usage, simplifying refactoring.
Part (b): ```java public class Book { private String isbn; private String title; private double price;
public double getPrice() { return this.price; } } ```
Part (c): ```java public static int binarySearchBook(Book[] books, String targetIsbn) { if (books == null || targetIsbn == null) { return -1; } int low = 0; int high = books.length - 1; while (low <= high) { int mid = (low + high) / 2; if (books[mid] != null) { int comparison = books[mid].getIsbn().compareTo(targetIsbn); if (comparison == 0) { return mid; } else if (comparison < 0) { low = mid + 1; } else { high = mid - 1; } } else { // Treat null element safety by narrowing boundary high--; } } return -1; } ```
PastPaper.markingScheme
Part (a) [3 marks total]: - 1 mark: Outlines restriction of direct data manipulation (private modifiers). - 1 mark: Mentions using interfaces/getters to isolate data changes safely. - 1 mark: Explains ease of maintainability (changes inside Book do not break code referencing it).
Part (b) [4 marks total]: - 1 mark: Declaring private instance variables with exact matching types. - 1 mark: Implementing Book constructor initializing instance variables. - 1 mark: Getters implemented with correct return signatures. - 1 mark: Maintaining overall formatting with correct Java syntax.
Part (c) [6 marks total]: - 1 mark: Correct method signature (public static int binarySearchBook(Book[], String)). - 1 mark: Checking for input arrays or parameters being null. - 1 mark: Setting up binary search boundaries (low = 0, high = books.length - 1). - 1 mark: Safe binary loop condition (low <= high) and calculation of middle index (mid). - 1 mark: Comparing isbn fields of object to target using compareTo() successfully. - 1 mark: Adjusting boundaries correctly based on comparison result, returning mid on match, and -1 on completion.
Paper 3 Case Study
Answer all questions based on the Rescue Robots Case Study booklet.
4 PastPaper.question · 30 PastPaper.marks
PastPaper.question 1 · Technical Analysis & Essay
7.5 PastPaper.marks
In urban search and rescue (USAR) environments, pre-existing communication infrastructure is often destroyed. Explain how rescue robots can establish a Mobile Ad-hoc Network (MANET) to dynamically route sensor data back to a central command station. Discuss two technical challenges specific to MANETs in collapsed structures and how they can be mitigated.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. **Establishing a MANET**: - Rescue robots act as both hosts and routers. They use short-range wireless protocols (such as Wi-Fi or ZigBee) to discover neighboring nodes. - They establish a peer-to-peer network without centralized infrastructure. Packets are routed multi-hop: if Robot A cannot reach the base station, it routes its packet through Robot B and Robot C. - Dynamic routing protocols (like AODV - Ad-hoc On-Demand Distance Vector, or DSR - Dynamic Source Routing) dynamically discover and update paths as robots move.
2. **Challenge 1: Signal Attenuation and Multipath Fading**: - *Description*: Structural materials (thick reinforced concrete, steel beams, soil) heavily absorb and reflect radio signals, causing high packet loss and dead zones. - *Mitigation*: Robots can deploy physical, static wireless transceiver 'breadcrumbs' (relay beacons) as they advance. These beacons maintain a line-of-sight chain back to the entrance.
3. **Challenge 2: Dynamic Topology and Network Partitioning**: - *Description*: As robots navigate deeper or get trapped, physical obstructions break active routes, partitioning the network. - *Mitigation*: Implementation of Delay-Tolerant Networking (DTN) routing. Instead of discarding packets when no route exists, nodes store data in non-volatile buffer memory and 'carry' it until they come into range of another node ('store-carry-forward' strategy).
PastPaper.markingScheme
Award up to 7.5 marks as follows: - **MANET Mechanism (2.5 marks)**: 1 mark for defining dynamic peer-to-peer self-configuration; 1 mark for explaining multi-hop routing/nodes acting as routers; 0.5 marks for naming or describing a routing protocol (e.g., AODV, reactive routing). - **Challenge 1 & Mitigation (2.5 marks)**: 1 mark for explaining signal attenuation due to materials (concrete/metal); 1.5 marks for a technically sound mitigation (e.g., deploying physical relay beacons/breadcrumbs, adaptive power control). - **Challenge 2 & Mitigation (2.5 marks)**: 1 mark for explaining path breakage/network partitioning due to movement or physical collapse; 1.5 marks for a technically sound mitigation (e.g., Delay-Tolerant Networking/DTN, store-carry-forward buffers, opportunistic routing).
PastPaper.question 2 · Technical Analysis & Essay
7.5 PastPaper.marks
Rescue robots must navigate through unstructured, debris-filled environments to locate survivors. To do this, they rely on Simultaneous Localization and Mapping (SLAM). Explain the concept of sensor fusion in the context of SLAM, detailing how data from an Inertial Measurement Unit (IMU) and a LiDAR sensor are combined. Analyze why relying on a single sensor type is insufficient for reliable mapping and localization in disaster zones.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. **Concept of Sensor Fusion in SLAM**: - Sensor fusion integrates data from multiple disparate sensors (e.g., IMU and LiDAR) to construct a more accurate state estimate (position, orientation, map) than any single sensor could produce alone. It mathematically mitigates individual sensor errors.
2. **Combining IMU and LiDAR Data**: - *Inertial Measurement Unit (IMU)*: Measures angular velocity and linear acceleration at very high frequencies (e.g., 200 Hz). It provides immediate updates on the robot's movement but suffers from integration drift (quadratic error growth over time). - *LiDAR (Light Detection and Ranging)*: Uses laser pulses to build a highly accurate 2D/3D point cloud of the environment at lower frequencies (e.g., 10 Hz). - *Fusion Process*: An Extended Kalman Filter (EKF) or Graph-SLAM algorithm is used. The IMU acts as the 'prediction' step, tracking fast state changes between LiDAR scans. The LiDAR point clouds are matched against the existing map (scan matching) to perform the 'correction' step, which resets the drift error accumulated by the IMU.
3. **Insufficiency of Single Sensors**: - *LiDAR alone*: Fails in dense smoke, dust, or airborne particulate matter (common in search and rescue), which reflects laser pulses prematurely. It also suffers from 'perceptual aliasing' in symmetrical long corridors where different locations look identical. - *IMU alone*: Is entirely blind to external landmarks. Without external corrections, its position estimate drifts by meters within seconds, making mapping impossible.
PastPaper.markingScheme
Award up to 7.5 marks as follows: - **Sensor Fusion Concept (1.5 marks)**: 1 mark for defining sensor fusion as combining complementary data to reduce overall uncertainty/error; 0.5 marks for reference to state estimation (pose/map). - **IMU and LiDAR Integration (3 marks)**: 1 mark for describing the characteristics/frequencies of IMU (high-frequency, drift-prone relative motion); 1 mark for LiDAR (highly accurate absolute spatial structure, lower frequency); 1 mark for explaining the fusion mechanics (e.g., prediction-correction loop, Kalman filtering, LiDAR correcting IMU drift). - **Single Sensor Insufficiency Analysis (3 marks)**: 1.5 marks for explaining a failure mode of LiDAR in disaster zones (dust, smoke, or perceptual mapping errors); 1.5 marks for explaining the failure mode of an IMU (cumulative mathematical drift rendering mapping impossible without external references).
PastPaper.question 3 · Technical Analysis & Essay
7.5 PastPaper.marks
A rescue operation utilizes a swarm of homogeneous autonomous micro-robots to search a grid-based disaster area. Rather than using centralized control, the robots employ a decentralized stigmergy-based coordination algorithm. Describe how stigmergy can be implemented digitally among the robots to optimize area coverage. Evaluate one advantage and one disadvantage of this decentralized approach compared to a centralized coordinator.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. **Digital Stigmergy Implementation**: - Stigmergy is indirect coordination mediated by the environment. Digitally, this is achieved by maintaining a shared, decentralized grid map. - When Robot A searches grid cell (X, Y), it writes a 'virtual pheromone' value (e.g., a timestamp of exploration) to its local grid representation. - This coordinate and timestamp are broadcasted locally to any nearby robots via short-range ad-hoc communication. - When Robot B approaches the same area, its sensors detect the digital pheromone (low timestamp value indicating recent exploration) on its updated local grid, prompting it to alter its heading toward areas with 'expired' or 'null' pheromone values.
2. **Evaluation: One Advantage**: - *Robustness / Fault Tolerance / Scalability*: Since there is no central coordinator, there is no single point of failure. If several robots are destroyed or drop offline, the remaining swarm continues to coordinate seamlessly using the localized environmental markers. The system easily scales up by adding more robots without increasing communication overhead at a central server.
3. **Evaluation: One Disadvantage**: - *Global Suboptimality / Path Inefficiency*: Because decisions are made purely on local, delayed environmental signals rather than a global structural view, robots may get stuck in local minima, repeatedly traverse boundary zones, or fail to prioritize high-risk areas as efficiently as a centralized coordinator using global pathfinding algorithms (like A* or Dijkstra's across the entire fleet).
PastPaper.markingScheme
Award up to 7.5 marks as follows: - **Stigmergy Implementation (3.5 marks)**: 1.5 marks for explaining environmental modification (concept of digital pheromones/shared local grids); 1 mark for detailing the communication/update mechanism (local broadcasting, timestamps, or grid state writes); 1 mark for describing the behavioral response (avoidance of high pheromone zones to maximize search coverage). - **Advantage Evaluation (2 marks)**: 1 mark for identifying a valid advantage (fault tolerance/no single point of failure, or horizontal scalability); 1 mark for explaining it in the context of a rescue scenario (e.g., robots being crushed or losing connection without stopping the mission). - **Disadvantage Evaluation (2 marks)**: 1 mark for identifying a valid disadvantage (suboptimal pathing, slow propagation of urgent global tasks); 1 mark for explaining how local-only information causes this inefficiency.
PastPaper.question 4 · Technical Analysis & Essay
7.5 PastPaper.marks
In rescue operations, robots rarely operate with absolute autonomy; instead, they use 'sliding autonomy' (adjustable autonomy). Define sliding autonomy and explain how a rescue robot transitions control between itself and a human operator during a high-risk task (such as manipulating a structural obstruction). Discuss how the system handles the latency ('time-delay') challenge inherent in long-distance remote control.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. **Definition and Transition of Sliding Autonomy**: - *Definition*: Sliding autonomy refers to a control scheme where the level of robot autonomy can be adjusted dynamically in real-time. The control spectrum ranges from pure manual teleoperation to supervised autonomy, and finally full autonomy. - *Transition of Control*: - When a robot encounters a complex manipulation task (like clearing heavy rubble), it operates autonomously until its onboard sensors detect a threshold violation (e.g., motor torque exceeding safe limits, or camera confidence dropping below 70%). - The robot halts, secures its posture, and issues a 'handover request' to the human operator. - The operator reviews the telemetry, takes manual control of the robotic arm via a haptic interface, executes the delicate manipulation, and then commands the robot to resume autonomous navigation.
2. **Handling Latency (Time-Delay)**: - *Predictive Simulation / Digital Twins*: The operator's control station runs a real-time, physics-based 3D simulation of the robot. When the operator inputs a command, the simulation shows the expected movement instantly, allowing the operator to guide the robot without waiting for the delayed video stream feedback. - *Local Autonomous Safeguards (Reflexes)*: The robot maintains low-level autonomous control loops locally. If the operator sends a delayed command that would cause the robot to crash into a wall, the local onboard proximity sensors override the human input, instantly halting the motors before the collision occurs.
PastPaper.markingScheme
Award up to 7.5 marks as follows: - **Sliding Autonomy Definition (1.5 marks)**: 1 mark for defining dynamic, real-time shifts in autonomy levels; 0.5 marks for identifying the range of control (manual, semi-autonomous, fully autonomous). - **Control Transition Mechanism (3 marks)**: 1 mark for explaining triggers (sensor thresholds, physical limits, user overrides); 2 marks for explaining a clear, logical step-by-step example of a control handover during a manipulation task (e.g., robot encounters high torque -> alerts operator -> operator takes over -> task completes -> handback). - **Latency Mitigation (3 marks)**: 1.5 marks for explaining a predictive/simulation-based strategy (digital twins, pre-rendered physics); 1.5 marks for explaining local autonomous reflex loops (onboard safety overrides to prevent delayed-command accidents).