IB DP · Thinka-original Practice Paper

2025 IB DP Computer Science Practice Paper with Answers

Thinka Nov 2025 SL IB Diploma Programme-Style Mock — Computer Science

115 marks150 mins2025
An original Thinka practice paper modelled on the structure and difficulty of the Nov 2025 SL IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.

Paper 1 Section A

Answer all questions in Section A.
10 Question · 25 marks
Question 1 · Short Answer
2.5 marks
Explain one disadvantage of a direct changeover compared to a parallel changeover when implementing a new computer system.
Show answer & marking scheme

Worked solution

Under direct changeover, the old system is completely shut down and replaced by the new system on a specific date. If the new system has critical, undetected bugs or fails entirely, there is no redundant system operating simultaneously (unlike in a parallel changeover). Consequently, the organization has no immediate fall-back option, leading to severe operational downtime or permanent loss of data.

Marking scheme

[1 mark] For explaining the mechanism of direct changeover (immediate cutoff with no overlap).
[1 mark] For identifying the consequence of failure (no backup/fall-back system available).
[0.5 marks] For linking this consequence to business disruption, operational downtime, or data loss.
Question 2 · Short Answer
2.5 marks
Identify two usability factors that must be considered when designing a digital interface for elderly users, and explain how one of these can be addressed.
Show answer & marking scheme

Worked solution

Elderly users often experience physical limitations such as declining visual acuity or reduced motor control (hand tremors). Two usability factors to address are text size/readability and target size (buttons). Text size can be addressed by designing a highly visible font with adjustable text scale settings and a high-contrast mode, allowing users with visual impairments to easily read the interface.

Marking scheme

[1 mark] For identifying two appropriate usability factors (e.g., font size, contrast, target click area size, simplicity of navigation layout).
[1 mark] For explaining a concrete interface design choice that addresses one of these factors.
[0.5 marks] For linking the design choice to the specific physical or cognitive limitation of elderly users (e.g., tremors, poor eyesight).
Question 3 · Short Answer
2.5 marks
Outline the specific role of the Program Counter (PC) during the fetch stage of the machine instruction cycle.
Show answer & marking scheme

Worked solution

At the beginning of the fetch stage, the Program Counter (PC) holds the memory address of the next instruction to be executed. This address is sent via the address bus to the Memory Address Register (MAR). Immediately after this address is copied, the Program Counter is incremented by 1 (or by the size of the instruction) so that it points to the memory address of the subsequent instruction for the next cycle.

Marking scheme

[1 mark] For stating that the Program Counter stores the address of the next instruction to be fetched.
[1 mark] For stating that this address is copied/sent to the Memory Address Register (MAR).
[0.5 marks] For stating that the Program Counter is incremented at the end of this phase to point to the next instruction.
Question 4 · Short Answer
2.5 marks
Explain why packets in a packet-switching network can arrive at their destination out of chronological order.
Show answer & marking scheme

Worked solution

In packet-switching networks, a data stream is divided into individual packets. Each packet is treated as an independent unit and routed dynamically. Routers determine the path for each packet based on current network state. Because of dynamic routing, packets can take different physical routes with varying lengths, hop counts, and traffic congestion. Some packets will experience longer latency than others, causing later-sent packets to arrive before earlier-sent packets.

Marking scheme

[1 mark] For explaining that packets are routed independently of one another.
[1 mark] For explaining that packets can take different physical paths/routes.
[0.5 marks] For explaining that differences in latency, path distance, or network congestion cause varying arrival times.
Question 5 · Short Answer
2.5 marks
Contrast the security provided by WPA2 (Wi-Fi Protected Access II) encryption with MAC address filtering in a wireless Local Area Network (LAN).
Show answer & marking scheme

Worked solution

WPA2 encrypts the actual data payload traveling over the wireless waves using strong encryption algorithms (like AES). This means even if an attacker intercepts the radio signals, they cannot decrypt the data. In contrast, MAC address filtering does not encrypt data; it simply checks the hardware address of the connecting device against an allowed list. Since MAC addresses are sent in plain text, an attacker can sniff a legitimate address and easily spoof it to gain access to the network.

Marking scheme

[1 mark] For describing how WPA2 provides data confidentiality through encryption.
[1 mark] For describing how MAC filtering operates purely on hardware identification and lacks encryption.
[0.5 marks] For contrasting their security levels (WPA2 is cryptographically secure, whereas MAC addresses are sent in plain text and easily spoofed).
Question 6 · Short Answer
2.5 marks
Define the term "decomposition" in computational thinking, and state one benefit of using it during software development.
Show answer & marking scheme

Worked solution

Decomposition is the process of breaking a complex problem or system into smaller, more manageable, and distinct parts. A key benefit of decomposition in software development is modularity: it allows multiple programmers to work on different components of the software in parallel, makes the code easier to test and debug, and increases the reusability of individual modules.

Marking scheme

[1 mark] For providing an accurate definition of decomposition (breaking a complex problem/system into smaller sub-units).
[1 mark] For stating a valid development benefit (e.g., parallel development, modularity, easier debugging/testing, code reusability).
[0.5 marks] For explaining how that benefit is achieved (e.g., by isolating tasks so different teams can focus on specific sub-components independently).
Question 7 · Short Answer
2.5 marks
State the maximum number of comparisons required to find a target value (or determine its absence) in a sorted array of 128 elements using a binary search algorithm. Show your calculation.
Show answer & marking scheme

Worked solution

In binary search, the worst-case scenario occurs when the search space is repeatedly halved until a single element remains. For an array size of \(N = 128\), the maximum number of steps/comparisons is calculated as:
\(\log_2(128) = 7\) comparison divisions.
In the worst case (unsuccessful search or finding the element on the final division), it requires at most \(\lfloor \log_2(128) \rfloor + 1 = 8\) comparisons.

Marking scheme

[1 mark] For stating the correct answer of 8 (or 7, depending on whether the final step evaluates to 1 element directly without an extra check; accept either 7 or 8 with matching logical calculation).
[1 mark] For showing the logarithmic relationship or the step-by-step halving of the array size (128 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1).
[0.5 marks] For explaining that the binary search works by splitting the sorted array in half at each iteration.
Question 8 · Short Answer
2.5 marks
Explain the relationship between inheritance and polymorphism in object-oriented programming (OOP).
Show answer & marking scheme

Worked solution

Inheritance allows a subclass (child class) to inherit attributes and methods from a superclass (parent class), establishing an "is-a" relationship. Polymorphism builds upon this relationship: it allows the program to process objects of different subclasses through a single common interface of the superclass. At runtime, the computer executes the specific overridden version of the method belonging to the subclass of the actual object, enabling dynamic binding.

Marking scheme

[1 mark] For explaining that inheritance establishes a class hierarchy where child classes inherit state and behavior from a parent class.
[1 mark] For explaining that polymorphism allows a single interface to represent different underlying forms (overriding inherited methods).
[0.5 marks] For explaining the connection (polymorphism requires inheritance or interfaces to dynamically resolve overridden behaviors at runtime).
Question 9 · Short Answer
2.5 marks
Distinguish between the terms 'usability' and 'accessibility' in relation to the design of a new software application.
Show answer & marking scheme

Worked solution

Usability is a measure of the overall user experience, focusing on factors like learnability, efficiency of use, memorability, error prevention, and user satisfaction. Accessibility, on the other hand, is a subset of usability that specifically addresses making the software inclusive and usable for people with disabilities (such as visual, auditory, cognitive, or physical impairments), often requiring compatibility with assistive technologies like screen readers.

Marking scheme

Award 1 mark for explaining usability (e.g., focusing on user efficiency, satisfaction, or general ease of use). Award 1 mark for explaining accessibility (e.g., focusing on inclusivity, removing barriers, or designing for users with diverse physical or cognitive impairments). Award 0.5 marks for a clear comparison or distinction that demonstrates how they relate (e.g., accessibility is a specific dimension of usability targeted at avoiding exclusion).
Question 10 · Short Answer
2.5 marks
A specific CPU utilizes a 12-bit address bus. Calculate the maximum number of unique memory locations that can be directly addressed by this CPU, and describe the primary function of the Memory Address Register (MAR) during the fetch stage of the instruction cycle.
Show answer & marking scheme

Worked solution

1. Calculations: A 12-bit address bus can address a maximum of \(2^{12}\) unique memory addresses, which equals 4096 locations. 2. Role of the MAR: During the fetch stage, the address stored in the Program Counter (PC) is copied to the MAR. The MAR then places this address on the address bus to point to the specific memory location in RAM from which the next instruction needs to be retrieved.

Marking scheme

Award 1 mark for the correct calculation of \(2^{12}\) or 4096 memory locations. Award 1 mark for stating that the MAR holds the address of the data or instruction currently being read from or written to RAM. Award 0.5 marks for describing its specific role during the fetch stage (e.g., receiving the address from the Program Counter and placing it onto the physical address bus).

Paper 1 Section B

Answer all questions in Section B.
3 Question · 45 marks
Question 1 · Structured Case Analysis & Programming
15 marks
A metropolitan public transit company is transitioning from its old magnetic stripe card ticketing system to a new contactless smart card system. The migration will affect millions of customer database records and real-time terminal devices across hundreds of stations.

(a) Identify two potential issues that could arise during the data migration process from the legacy database to the new system database. [2 marks]

(b) Explain the role and significance of running a 'beta testing' phase with a group of commuters before launching the contactless system to the general public. [3 marks]

(c) Compare the implementation methods of 'direct changeover' and 'parallel running' for this transit system. In your comparison, describe each method and identify one distinct advantage and one distinct disadvantage of each in this specific context. [4 marks]

(d) The transit company implements a weekly fare capping policy. Passengers are charged for individual rides until their cumulative weekly spend reaches $30.00. Once the cap is reached, all subsequent rides within that calendar week are free ($0.00 charge). If a single ride's fare would cause the total weekly spend to exceed $30.00, the passenger is only charged the exact difference to reach the $30.00 cap.

Construct a pseudocode algorithm for the method calculateFare(weeklySpent, rawFare) which:
- Accepts weeklySpent (the passenger's total fare paid so far this week) and rawFare (the standard cost of the current single ride).
- Returns the actual fare that should be charged to the passenger for the current ride based on the capping policy. [6 marks]
Show answer & marking scheme

Worked solution

(a) Data migration issues include:
1. Incompatible data formats between the old system databases and the new database schema (e.g., mismatching fields, card sequence limits).
2. Loss of balance or user profile data during export/import processes due to connection issues or database validation mismatches.

(b) Beta testing exposes the contactless ticketing system to actual commuters under real-world conditions. This uncovers edge-case software/hardware bugs (such as card-reading lag at turnstiles) that laboratory testing cannot replicate. It also lets developers gather qualitative feedback on the user interfaces (sounds, screens) to refine usability before the full public release.

(c) Direct Changeover involves completely shutting off the old magnetic card system and starting the contactless system instantly.
Advantage: Low cost with no need to run dual physical components or databases concurrently.
Disadvantage: Extremely high risk; if it fails, transit operations halt.

Parallel Running operates both old and new systems simultaneously.
Advantage: Zero disruption as the old system serves as a live backup if the new system fails.
Disadvantage: Extremely costly and operationally complex to sync dual databases and physical turnstiles.

(d) Pseudocode:
method calculateFare(weeklySpent, rawFare)
if weeklySpent >= 30.0 then
return 0.0
else if (weeklySpent + rawFare) > 30.0 then
return 30.0 - weeklySpent
else
return rawFare
end if
end method

Marking scheme

Part (a) [2 marks]:
- Award 1 mark for each valid, distinct migration issue identified up to 2 marks (e.g., incompatible formats, data loss, incomplete user files, corruption).

Part (b) [3 marks]:
- 1 mark for identifying that beta testing involves end-users (commuters) in real scenarios.
- 1 mark for explaining that it reveals real-world hardware/software edge cases.
- 1 mark for highlighting feedback on usability or operational speed.

Part (c) [4 marks]:
- 1 mark for defining direct changeover with its distinct advantage/disadvantage.
- 1 mark for defining parallel running with its distinct advantage/disadvantage.
- 2 marks for analytical comparison showing clear balance of risk vs cost within the transit context.

Part (d) [6 marks]:
- 1 mark: Correct method signature and parameter names.
- 1 mark: Valid base condition checking if weeklySpent >= 30.0 and returning 0.0.
- 2 marks: Correct condition for partial cap reach (weeklySpent + rawFare > 30.0) and calculating correct return value (30.0 - weeklySpent).
- 1 mark: Else condition returning the regular rawFare.
- 1 mark: Correct logical structures (proper nesting/sequence structure, and end statement).
Question 2 · Structured Case Analysis & Programming
15 marks
A school network administrator is planning to deploy a massive Bring Your Own Device (BYOD) wireless infrastructure to replace their old wired network.

(a) Identify two benefits of using a wireless local area network (WLAN) compared to a wired network in an educational environment. [2 marks]

(b) Explain how implementing Virtual Local Area Networks (VLANs) improves both security and traffic management for this school network. [4 marks]

(c) Describe the four-step process used by the DHCP protocol (often referred to as DORA) when a student's tablet connects to the network and requests an IP address. [4 marks]

(d) Explain how wireless encryption protocols (such as WPA3) prevent unauthorized interception and reading of user data on a wireless network. [5 marks]
Show answer & marking scheme

Worked solution

(a) Benefits of WLAN in school:
1. Mobility: Students and teachers can access learning resources seamlessly anywhere on campus (classroom, library, courtyard).
2. Scalability/Cost: Easily supports hundreds of personal devices without running thousands of expensive physical cables to desks.

(b) VLAN logical partitioning benefits:
1. Security: Isolates student devices from administrative systems (containing grades, financial information, staff communications). Even if a student's device is compromised, malware cannot easily propagate to the admin subnet.
2. Traffic Management: Restricts broad broadcast domains, ensuring multicast protocols do not saturate the entire school's bandwidth. Bandwidth can be partitioned, prioritizing teacher video conferencing over student gaming traffic.

(c) DHCP DORA Process:
1. Discover: Client broadcasts a DHCP Discover packet to locate available DHCP servers.
2. Offer: DHCP servers propose an IP configuration (IP, subnet, default gateway) in a DHCP Offer packet.
3. Request: Client broadcasts a DHCP Request packet, selecting and accepting the specific offered parameters.
4. Acknowledge (ACK): Server sends a DHCP ACK packet, completing the handshake and leasing the IP address to the client.

(d) Wireless encryption details:
1. Wireless radio waves broadcast in all directions, permitting passive sniffing of packet content by anyone in geographic range.
2. WPA3 encrypts data payloads using cryptographic mathematical algorithms, transforming plaintext into ciphertext before it is broadcast.
3. Each user session utilizes unique session keys negotiated during initialization (using SAE protocol in WPA3).
4. Unauthorized interceptors without the proper mathematical key see only unreadable garbled data, maintaining user data confidentiality even on shared campus networks.

Marking scheme

Part (a) [2 marks]:
- Award 1 mark for each valid, distinct advantage identified up to 2 marks (mobility, flexibility, reduced installation/cabling cost, support for BYOD devices).

Part (b) [4 marks]:
- 1 mark: Explaining VLAN partition logic.
- 1 mark: Connecting VLAN to security isolation (preventing unauthorized cross-access to sensitive admin data).
- 1 mark: Explaining traffic management (broadcast containment).
- 1 mark: Contextualizing to a school's actual user groups (students vs. administration).

Part (c) [4 marks]:
- 1 mark for each step of DORA correctly described:
- Discover (Client broadcast search)
- Offer (Server address configuration recommendation)
- Request (Client selection acknowledgement)
- Acknowledge/ACK (Server lease confirmation)

Part (d) [5 marks]:
- 1 mark: Highlighting wireless signals as open media vulnerable to interception/sniffing.
- 1 mark: Defining encryption as converting plaintext to ciphertext.
- 1 mark: Explaining that keys are needed for decryption.
- 1 mark: Explaining WPA3's robust session-specific protection.
- 1 mark: Stating the resulting preservation of privacy/confidentiality for sensitive client transactions.
Question 3 · Structured Case Analysis & Programming
15 marks
A printer server manages print jobs using three distinct queues depending on the job's priority (High, Medium, and Low). When the server has capacity, it retrieves the next job to print.

(a) Define the term abstract data type (ADT). [2 marks]

(b) Distinguish between a standard queue and a priority queue in terms of their insertion and deletion operations. [3 marks]

(c) State one disadvantage of using an array to implement a queue instead of using a dynamic linked list. [2 marks]

(d) A printer server manages print jobs using three distinct queues of a standard Queue class: highQueue, medQueue, and lowQueue.
Each Queue object supports the following operations:
- isEmpty(): returns true if there are no elements left in the queue, false otherwise.
- dequeue(): removes and returns the first item from the front of the queue.

Write an algorithm in pseudocode for the method getNextJob() that:
- Checks the queues in order of priority (High first, then Medium, then Low).
- Removes and returns the first job from the highest-priority non-empty queue.
- Returns null if all three queues are empty. [8 marks]
Show answer & marking scheme

Worked solution

(a) An Abstract Data Type (ADT) is a logical specification of a data structure and its associated behaviors (operations), which separates the user-facing interface from the concrete low-level implementation details in any particular programming language.

(b) Differences:
1. Standard Queue: Operates on strict First-In-First-Out (FIFO) rules. Elements are appended only at the tail (rear) and pulled strictly from the head (front).
2. Priority Queue: Elements are assigned a priority rank. Regardless of arrival time, elements with higher priority are dequeued (deleted) before lower priority items. Alternatively, insertion sorts elements immediately by priority rank.

(c) Disadvantage of array-based queue:
Arrays are static data structures, meaning they have a fixed maximum capacity declared upon initiation. This can lead to queue overflow errors if print volumes peak, or memory waste if overallocated. Furthermore, standard non-circular array queue deletions require shifting elements left, which is an inefficient O(N) operation compared to a O(1) pointer reassignment in linked lists.

(d) Pseudocode Implementation:
method getNextJob()
if not highQueue.isEmpty() then
return highQueue.dequeue()
else if not medQueue.isEmpty() then
return medQueue.dequeue()
else if not lowQueue.isEmpty() then
return lowQueue.dequeue()
else
return null
end if
end method

Marking scheme

Part (a) [2 marks]:
- 1 mark for conceptual modeling/definition of data and methods.
- 1 mark for highlighting implementation independence (separation of interface from coding details).

Part (b) [3 marks]:
- 1 mark: Explaining standard queue FIFO behavior.
- 1 mark: Explaining priority queue priority-based deletion behavior.
- 1 mark: Contrast demonstrating how priority overrides chronological sequence.

Part (c) [2 marks]:
- 1 mark: Pointing out static size limitation (leading to overflow/waste) or shifting overhead.
- 1 mark: Explaining how dynamic linked lists avoid this via runtime node allocation and pointers.

Part (d) [8 marks]:
- 1 mark: Correct method signature declaration (method getNextJob() and matching end).
- 2 marks: Correctly checking if highQueue is not empty (using .isEmpty()) and returning .dequeue().
- 2 marks: Correctly structured fallback to medQueue if highQueue was empty.
- 2 marks: Correctly structured fallback to lowQueue if both upper tiers are empty.
- 1 mark: Correctly returning null when all conditions are exhausted, maintaining syntactic clarity.

Paper 2 Option D

Answer all questions from Option D.
3 Question · 45 marks
Question 1 · subjective
15 marks
A fitness tracking application manages user workout sessions. The design is represented by a set of classes: Activity, Run, and UserAccount.

- An Activity object represents a general physical exercise. It contains attributes such as id (String), durationMinutes (int), and caloriesBurned (double).
- A Run object is a specialized type of Activity that includes an additional attribute averagePace (double).
- A UserAccount object maintains an array of completed exercises, defined as: private Activity[] completedActivities.

(a) Describe the relationship between Activity and Run, and the relationship between UserAccount and Activity. [4]

(b) Construct the Java code for the Activity class. It must include:
- private attributes: id (String), durationMinutes (int), and caloriesBurned (double).
- A constructor with parameters for all three attributes.
- Accessor (getter) methods for all attributes.
- A method calculateIntensity() that returns a String: "Low" if calories burned per minute are less than 5; "Medium" if they are between 5 and 10 inclusive; and "High" if they are greater than 10. (Assume durationMinutes is always greater than 0). [6]

(c) Construct a method in the UserAccount class: public double getTotalCaloriesByIntensity(String intensity). This method must loop through the completedActivities array, calculate the intensity for each activity, and return the sum of the calories burned for all activities matching the specified intensity. Note: You must handle any null elements in the array. [5]
Show answer & marking scheme

Worked solution

Part (a)
- The relationship between Activity and Run is inheritance (or an "is-a" relationship). Run extends Activity, meaning Run inherits all attributes and behaviors of Activity while adding its own specific property (averagePace).
- The relationship between UserAccount and Activity is aggregation (or a "has-a" relationship). UserAccount holds references to multiple Activity objects in an array. The lifetime of Activity objects is independent of the UserAccount object (i.e., deleting a UserAccount does not necessarily destroy the activities if they are tracked elsewhere).

Part (b)
```java
public class Activity {
private String id;
private int durationMinutes;
private double caloriesBurned;

public Activity(String id, int durationMinutes, double caloriesBurned) {
this.id = id;
this.durationMinutes = durationMinutes;
this.caloriesBurned = caloriesBurned;
}

public String getId() {
return this.id;
}

public int getDurationMinutes() {
return this.durationMinutes;
}

public double getCaloriesBurned() {
return this.caloriesBurned;
}

public String calculateIntensity() {
double rate = this.caloriesBurned / this.durationMinutes;
if (rate < 5) {
return "Low";
} else if (rate <= 10) {
return "Medium";
} else {
return "High";
}
}
}
```

Part (c)
```java
public double getTotalCaloriesByIntensity(String intensity) {
double total = 0.0;
for (int i = 0; i < completedActivities.length; i++) {
if (completedActivities[i] != null) {
if (completedActivities[i].calculateIntensity().equals(intensity)) {
total += completedActivities[i].getCaloriesBurned();
}
}
}
return total;
}
```

Marking scheme

Part (a): [4 Marks]
- [1 mark] for identifying the relationship between Activity and Run as Inheritance.
- [1 mark] for explaining that Run is a subclass of Activity and inherits its properties.
- [1 mark] for identifying the relationship between UserAccount and Activity as Aggregation / Association.
- [1 mark] for explaining that UserAccount contains/has a collection of Activity objects.

Part (b): [6 Marks]
- [1 mark] for declaring the three private instance variables with correct data types.
- [1 mark] for the correct constructor initialization of these three variables.
- [1 mark] for correct implementations of accessor (getter) methods.
- [1 mark] for calculating the correct rate of calories burned per minute: caloriesBurned / durationMinutes.
- [2 marks] for implementing correct conditional logic (if-else structure) to return "Low", "Medium", and "High" correctly based on the rate threshold.

Part (c): [5 Marks]
- [1 mark] for initializing a total counter to 0.0.
- [1 mark] for setting up a correct loop through the array length.
- [1 mark] for checking if the current element is not null before accessing its methods.
- [1 mark] for correctly matching the returned intensity string using .equals(intensity).
- [1 mark] for correctly summing the matching values and returning the final total variable.
Question 2 · subjective
15 marks
A digital library offers different media types for streaming. It models its catalog using an inheritance hierarchy.

(a) Define the term polymorphism and outline how it would allow a unified search process to output the licensing fee for a list containing both Movie and Series objects. [4]

(b) Construct the Java code for the abstract base class MediaContent, which must contain:
- Private instance variables: title (String) and basePrice (double).
- A constructor with parameters for both variables.
- Appropriate public accessor methods.
- An abstract method public abstract double getLicensingFee(). [5]

(c) Construct the Java code for the Movie subclass of MediaContent, which must contain:
- An additional private instance variable: duration (int, representing minutes).
- A constructor initializing title, basePrice, and duration using the superclass constructor appropriately.
- An implementation of getLicensingFee() that overrides the parent abstract method. If duration is greater than 120 minutes, the licensing fee is basePrice plus $0.05 for every minute above 120. Otherwise, the licensing fee is simply basePrice. [6]
Show answer & marking scheme

Worked solution

Part (a)
- Polymorphism is the ability of different objects to respond to the same message (method call) in different ways based on their class definition.
- In this scenario, both Movie and Series inherit from MediaContent, and both implement the abstract method getLicensingFee() with different logic.
- A program can iterate through a single collection (such as an array or list) of type MediaContent, call contentItem.getLicensingFee() on each item, and Java's dynamic binding will execute the overridden subclass method depending on whether the object is actually a Movie or a Series.

Part (b)
```java
public abstract class MediaContent {
private String title;
private double basePrice;

public MediaContent(String title, double basePrice) {
this.title = title;
this.basePrice = basePrice;
}

public String getTitle() {
return this.title;
}

public double getBasePrice() {
return this.basePrice;
}

public abstract double getLicensingFee();
}
```

Part (c)
```java
public class Movie extends MediaContent {
private int duration;

public Movie(String title, double basePrice, int duration) {
super(title, basePrice);
this.duration = duration;
}

public int getDuration() {
return this.duration;
}

@Override
public double getLicensingFee() {
if (this.duration > 120) {
int extraMinutes = this.duration - 120;
return this.getBasePrice() + (extraMinutes * 0.05);
} else {
return this.getBasePrice();
}
}
}
```

Marking scheme

Part (a): [4 Marks]
- [1 mark] for a valid definition of polymorphism (objects showing different behaviors to the same method call).
- [1 mark] for noting that dynamic binding (run-time polymorphism) resolves the method call at execution time.
- [1 mark] for explaining that a single array/collection of MediaContent can store both Movie and Series objects.
- [1 mark] for showing that calling .getLicensingFee() in a loop will call the correct specific formula for each class without explicit casting.

Part (b): [5 Marks]
- [1 mark] for declaring the class as abstract with correct syntax: public abstract class MediaContent.
- [1 mark] for defining the private instance variables with proper data types.
- [1 mark] for the correct constructor initialization of title and basePrice.
- [1 mark] for implementing appropriate public getter methods.
- [1 mark] for the correct abstract method signature: public abstract double getLicensingFee(); (with no method body).

Part (c): [6 Marks]
- [1 mark] for declaring subclass inheritance using extends MediaContent.
- [1 mark] for implementing private field duration and calling super(title, basePrice) correctly inside the constructor.
- [1 mark] for correctly implementing a getter for duration.
- [1 mark] for overriding the method signature public double getLicensingFee().
- [1 mark] for writing a conditional branch checking if duration > 120.
- [1 mark] for accurately calculating and returning the licensing fee in both conditional branches using getBasePrice() (or super.getBasePrice()).
Question 3 · subjective
15 marks
An automated sorting facility uses StorageShelf objects to hold Box objects.

- Each Box object has private attributes weight (double) and contents (String), with accessor methods getWeight() and getContents().
- A StorageShelf object holds a fixed-size array of Box objects, defined as:
private Box[] shelves;
The array is initialized in the constructor to hold a specific capacity (e.g., 5 elements).

(a) Explain the difference between aggregation and composition, and justify which of these relationships is most appropriate to describe the connection between StorageShelf and Box. [4]

(b) Construct a Java method for the StorageShelf class: public boolean addBox(Box newBox). This method should locate the first empty slot (a slot with a value of null) in the shelves array, insert the newBox into that slot, and return true. If no empty slots exist, the method must return false. [5]

(c) Construct a Java method for the StorageShelf class: public Box removeHeaviest(). This method must find the Box with the maximum weight stored in the shelves array. It must then set that index in the shelves array to null to remove the Box, and return the removed Box object. If the shelves array is completely empty (all slots are null), return null. [6]
Show answer & marking scheme

Worked solution

Part (a)
- Composition implies a strong ownership relationship where the child object cannot exist independently of the parent object. If the parent object is destroyed, the child objects are also destroyed.
- Aggregation implies a weaker relationship where the child object can exist independently of the parent container.
- For StorageShelf and Box, aggregation is more appropriate because boxes are physically independent physical entities. When a shelf is deleted or dismantled, the boxes themselves are simply relocated or kept in storage elsewhere; they do not cease to exist.

Part (b)
```java
public boolean addBox(Box newBox) {
for (int i = 0; i < shelves.length; i++) {
if (shelves[i] == null) {
shelves[i] = newBox;
return true;
}
}
return false;
}
```

Part (c)
```java
public Box removeHeaviest() {
double maxWeight = -1.0;
int heaviestIndex = -1;

for (int i = 0; i < shelves.length; i++) {
if (shelves[i] != null) {
if (shelves[i].getWeight() > maxWeight) {
maxWeight = shelves[i].getWeight();
heaviestIndex = i;
}
}
}

if (heaviestIndex != -1) {
Box heaviestBox = shelves[heaviestIndex];
shelves[heaviestIndex] = null;
return heaviestBox;
}

return null;
}
```

Marking scheme

Part (a): [4 Marks]
- [1 mark] for defining Composition (strong ownership, lifecycle dependency).
- [1 mark] for defining Aggregation (weak relationship, independent lifecycles).
- [1 mark] for identifying that the relationship here is Aggregation.
- [1 mark] for justifying that Box objects can exist independently of any specific StorageShelf (e.g., they can be moved to another shelf, truck, or floor).

Part (b): [5 Marks]
- [1 mark] for correct method header public boolean addBox(Box newBox).
- [1 mark] for implementing a loop iterating through the length of the shelves array.
- [1 mark] for executing a null check condition on current elements: shelves[i] == null.
- [1 mark] for correctly assigning shelves[i] = newBox inside the block and returning true immediately.
- [1 mark] for returning false after the loop completes if no null slot was found.

Part (c): [6 Marks]
- [1 mark] for initializing state variables to track the maximum weight (e.g., -1.0) and the index of the heaviest Box (e.g., -1).
- [1 mark] for a correct loop through the entire shelves array.
- [1 mark] for verifying that the slot is not null prior to checking its properties.
- [1 mark] for correctly using getWeight() to compare and update the maximum weight and tracked index.
- [1 mark] for checking if a valid index was found, saving the reference, and clearing the slot (setting it to null).
- [1 mark] for returning the correct Box reference, or returning null if no Box was found on the shelf.

Wondering how well you actually know this?

Thinka is an AI practice app for DSE students — unlimited questions, instant auto-marking, and detailed step-by-step solutions. 100,000+ students use it to confirm they actually know it, not just think they do.

Want more questions like this? Practice unlimited on Thinka — instant answers included.

Start Practising Free