IB DP · PastPaper.sampleTitle

MetadataPastPaper.sampleTitle

Thinka May 2025 SL (TZ2) IB Diploma Programme-Style Mock — Computer Science

115 PastPaper.marks150 PastPaper.minutes2025
An original Thinka practice paper modelled on the structure and difficulty of the May 2025 SL (TZ2) IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.

Paper 1 Section A

Answer all questions in this section. Short response questions and foundational trace tables.
8 PastPaper.question · 22 PastPaper.marks
PastPaper.question 1 · Outline
2 PastPaper.marks
Outline one disadvantage of using a prototype during the system development life cycle.
PastPaper.showAnswers

PastPaper.workedSolution

A prototype is an early, simplified model of a system. A primary disadvantage is that users or clients may get a false impression of development progress. Because they see a functional user interface, they might assume the entire software is nearly finished, neglecting the complex backend development, security features, and error handling that still need to be built. This can lead to scope creep or client dissatisfaction when the final release takes much longer than they anticipated.

PastPaper.markingScheme

Award 1 mark for identifying a valid disadvantage (e.g., misleading expectations, scope creep, additional development time/costs). Award 1 mark for outlining how this disadvantage impacts the project or client relationship (e.g., users believing the system is complete when backend systems are missing, leading to premature release pressure).
PastPaper.question 2 · State
2 PastPaper.marks
State two benefits of a school implementing a Virtual Private Network (VPN) to allow teachers to work remotely from home.
PastPaper.showAnswers

PastPaper.workedSolution

A Virtual Private Network (VPN) creates an encrypted tunnel over a public connection. This allows school staff to transmit sensitive records securely without the threat of unauthorized interception. Additionally, it authenticates remote teachers and assigns them an internal IP address, granting them secure access to school servers and local databases that are otherwise restricted from public internet access.

PastPaper.markingScheme

Award 1 mark for each valid benefit stated, up to a maximum of 2 marks. Acceptable answers include: Secure encrypted data transmission, Remote access to restricted internal drives/databases, Masking of the remote user's geographic location/IP address, and User authentication before accessing school networks.
PastPaper.question 3 · Identify
2 PastPaper.marks
Identify the role of the Program Counter (PC) register in the central processing unit (CPU) during the fetch stage of the Machine Instruction Cycle.
PastPaper.showAnswers

PastPaper.workedSolution

The Program Counter (PC) register acts as a pointer to the next instruction in sequence. During the fetch stage, its value is copied to the Memory Address Register (MAR) so that the control unit can fetch the instruction from RAM. Immediately after this address transfer, the PC is incremented (usually by 1) so that it is prepped to point to the subsequent instruction in the next cycle.

PastPaper.markingScheme

Award 1 mark for identifying that the PC holds or points to the memory address of the next instruction to be fetched. Award 1 mark for identifying that its address value is copied to the MAR, OR that the PC is incremented immediately after the transfer.
PastPaper.question 4 · Outline
2 PastPaper.marks
Outline the difference between a variable and a constant in computer programming.
PastPaper.showAnswers

PastPaper.workedSolution

The distinction lies in mutability. Variables are allocated memory blocks where data can be overwritten or updated as the algorithm processes input (e.g., count = count + 1). Constants are defined with a permanent value at the outset of the program (e.g., PI = 3.1415) to prevent accidental modification, ensuring integrity throughout execution.

PastPaper.markingScheme

Award 1 mark for explaining that a variable's value can change or be reassigned during runtime. Award 1 mark for explaining that a constant's value is immutable or fixed once defined and cannot be updated during runtime.
PastPaper.question 5 · Outline
2 PastPaper.marks
Outline one benefit of choosing a direct changeover method instead of a parallel running method when deploying a new computerized system.
PastPaper.showAnswers

PastPaper.workedSolution

With a direct changeover, the old system is immediately stopped and the new system is fully launched. This is highly beneficial because it eliminates double-data entry and additional administrative overhead. In contrast, parallel running requires employees to execute tasks in both systems simultaneously, which nearly doubles the operational cost and workforce effort.

PastPaper.markingScheme

Award 1 mark for identifying a valid benefit of direct changeover (e.g., lower cost, less time, immediate availability of features, no duplicate work). Award 1 mark for explaining how this benefit is achieved (e.g., by avoiding the high cost and staff resource double-entry associated with running both systems concurrently in parallel running).
PastPaper.question 6 · Outline
2 PastPaper.marks
Outline how Carrier Sense Multiple Access with Collision Avoidance (CSMA/CA) prevents data collisions on a wireless local area network (WLAN).
PastPaper.showAnswers

PastPaper.workedSolution

In a wireless environment, nodes cannot listen for collisions while actively transmitting. Under CSMA/CA, a node wishing to transmit must first sense (listen to) the wireless medium. If the channel is busy, it waits. If it is idle, it waits for a random back-off duration to ensure another waiting node does not transmit at the same time. It can also send a Request to Send (RTS) packet, and wait for a Clear to Send (CTS) packet from the access point, thereby reserving the airwaves and preventing other nodes from causing collisions.

PastPaper.markingScheme

Award 1 mark for explaining that the device first performs carrier sensing (listens to the medium to check if it is busy/idle). Award 1 mark for explaining the collision avoidance technique (e.g., waiting a random back-off time if the medium is busy, or using RTS/CTS frames to reserve transmission space).
PastPaper.question 7 · Logic Diagram Construction
4 PastPaper.marks
An automated greenhouse ventilation system activates a fan (\(F\)) based on three inputs: High Temperature (\(T\)), High Humidity (\(H\)), and Manual Override (\(M\)).

The fan is activated (\(F = 1\)) if Manual Override is active, OR if both High Temperature and High Humidity are detected simultaneously.

Construct a logic diagram for this system, clearly showing all inputs, logic gates, and the final output.
PastPaper.showAnswers

PastPaper.workedSolution

The Boolean expression representing this system is: \(F = M + (T \cdot H)\) or \(F = M \lor (T \land H)\).

To construct the logic diagram:
1. Connect the inputs \(T\) and \(H\) to the inputs of a two-input AND gate.
2. Connect the output of this AND gate and the input \(M\) to the inputs of a two-input OR gate.
3. Label the output of the OR gate as \(F\).

Visual Diagram representation:
```
T --------| \\
| )--- [AND] ----\
H --------| // |
|------| \\
| )--- [OR] ----> F
M ---------------------------------| //
```

PastPaper.markingScheme

Award up to [4 marks] as follows:
- Award [1 mark] for drawing/identifying a two-input AND gate.
- Award [1 mark] for drawing/identifying a two-input OR gate.
- Award [1 mark] for correctly routing inputs T and H into the AND gate.
- Award [1 mark] for correctly routing input M and the output of the AND gate into the OR gate, with the final output clearly labeled as F.
PastPaper.question 8 · Trace Table
6 PastPaper.marks
Consider the following pseudocode algorithm:

```
VALS = [5, 12, 8, 3, 15]
LIMIT = 10
X = 0
Y = 0
loop I from 0 to 4
A = VALS[I]
if A < LIMIT then
X = X + A
else
Y = Y + 1
end if
end loop
```

Construct a trace table for this algorithm. Your trace table should show the state of the variables and conditions at each step of the loop, starting from the initial states before the loop commences.
PastPaper.showAnswers

PastPaper.workedSolution

To solve this problem, we trace the execution step-by-step:

1. **Initialization**:
- `X` is initialized to `0`.
- `Y` is initialized to `0`.

2. **Iteration I = 0**:
- `VALS[0]` is `5`.
- `A` is assigned `5`.
- The condition `A < LIMIT` (i.e., `5 < 10`) evaluates to `True`.
- `X` becomes `X + A` = `0 + 5 = 5`.
- `Y` remains `0`.

3. **Iteration I = 1**:
- `VALS[1]` is `12`.
- `A` is assigned `12`.
- The condition `A < LIMIT` (i.e., `12 < 10`) evaluates to `False`.
- `Y` becomes `Y + 1` = `0 + 1 = 1`.
- `X` remains `5`.

4. **Iteration I = 2**:
- `VALS[2]` is `8`.
- `A` is assigned `8`.
- The condition `A < LIMIT` (i.e., `8 < 10`) evaluates to `True`.
- `X` becomes `X + A` = `5 + 8 = 13`.
- `Y` remains `1`.

5. **Iteration I = 3**:
- `VALS[3]` is `3`.
- `A` is assigned `3`.
- The condition `A < LIMIT` (i.e., `3 < 10`) evaluates to `True`.
- `X` becomes `X + A` = `13 + 3 = 16`.
- `Y` remains `1`.

6. **Iteration I = 4**:
- `VALS[4]` is `15`.
- `A` is assigned `15`.
- The condition `A < LIMIT` (i.e., `15 < 10`) evaluates to `False`.
- `Y` becomes `Y + 1` = `1 + 1 = 2`.
- `X` remains `16`.

PastPaper.markingScheme

Award marks as follows (up to 6 marks maximum):
- **[1 mark]** for correctly showing the initial state of `X = 0` and `Y = 0` before the loop starts.
- **[1 mark]** for correctly tracing the sequence of loop indices `I` from `0` to `4` (and associated `VALS[I]` values).
- **[1 mark]** for correctly tracking the variable `A` at each iteration.
- **[1 mark]** for correctly evaluating the condition `A < LIMIT` (as `True`/`False` or `T`/`F`) at each step.
- **[1 mark]** for correctly updating variable `X` at each correct step (ending with value `16`).
- **[1 mark]** for correctly updating variable `Y` at each correct step (ending with value `2`).

*Acceptance Notes: Accept alternative representations where values are only written when they change, or fully repeated across all rows. Accept alternative boolean representations like T/F, Yes/No, or 1/0 for the conditional check.*

Paper 1 Section B

Answer all questions in this section. Scenario-based structured responses and pseudocode algorithm creation.
3 PastPaper.question · 45 PastPaper.marks
PastPaper.question 1 · Structured
17 PastPaper.marks
AeroForm Solutions is a manufacturing company that specializes in producing custom aerodynamic components. The company has decided to replace its decade-old local desktop CAD (Computer-Aided Design) system with a modern, cloud-based collaborative CAD platform. (a) Identify two organizational issues that AeroForm Solutions may face when implementing this new cloud-based system. [2] (b) Describe one method of testing the compatibility of legacy CAD files with the new system before complete migration. [3] (c) Compare the direct changeover method with the phased introduction method for migrating to the new CAD system. [4] (d) Explain the role of prototype versions during the design phase of the new system's user interface. [4] (e) Suggest two reasons why user documentation is essential for the successful implementation of this new software. [4]
PastPaper.showAnswers

PastPaper.workedSolution

(a) Two organizational issues: 1. User resistance to change from designers accustomed to the legacy system. 2. Costs and time required for retraining staff on the new cloud-based interface and collaborative workflow. (b) Compatibility testing method: Sandbox/sample migration testing. A representative sample of legacy CAD files (varying in format, age, and complexity) is imported into a non-production test environment of the new cloud CAD system. The resulting models are visually and structurally compared to the originals to identify rendering errors, scale issues, or missing metadata. (c) Comparison of migration methods: Direct changeover involves completely stopping the legacy system and immediately starting the new cloud CAD system on a set date. It is fast and cheap but highly risky; any failure halts all design operations. Phased introduction involves migrating parts of the organization (e.g., one design department at a time) to the new system. It lowers risk because failures are localized, but it increases complexity as the organization must manage and coordinate two different systems simultaneously. (d) Role of prototype versions: Prototypes allow designers to experience and interact with a mock-up of the user interface early in development. This facilitates immediate feedback on navigation, tool placement, and accessibility, enabling developers to identify design flaws and revise usability requirements before expensive backend coding is completed. (e) Importance of user documentation: 1. It acts as an ongoing reference and troubleshooting manual, reducing the burden on the IT support helpdesk. 2. It standardizes workflows and reduces operational errors during the initial transition period, maintaining productivity.

PastPaper.markingScheme

Part (a): Award 1 mark for each valid organizational issue identified, up to 2 marks. Valid points include: user resistance, retraining costs/time, workflow disruption during transition, data governance policies. Part (b): Award 1 mark for identifying a valid testing method (e.g., sample-based dry run, sandbox testing). Award 1 mark for describing the process (e.g., selecting a diverse range of historical files to import). Award 1 mark for detailing the evaluation/verification step (e.g., cross-checking dimensions and integrity in the new system). Part (c): Award up to 2 marks for direct changeover: 1 mark for describing the immediate switch/cost advantage, 1 mark for identifying the high operational risk of system failure. Award up to 2 marks for phased introduction: 1 mark for describing the gradual/departmental rollout, 1 mark for explaining the balance of lower risk versus higher complexity of maintaining dual systems. Part (d): Award 1 mark per distinct point up to 4 marks: - Establishes an early feedback loop with end-users. - Identifies usability flaws and interface issues before full-scale coding. - Saves development costs by making corrections early. - Demonstrates system requirements visually to stakeholders. Part (e): Award 1 mark for identifying a reason and 1 mark for explaining its impact/benefit to the implementation, repeated for two reasons (up to 4 marks). Valid reasons: reduces helpdesk load, speeds up training/onboarding, minimizes operator errors during CAD operations, preserves institutional knowledge.
PastPaper.question 2 · structured
15 PastPaper.marks
PixelCraft is a digital marketing agency with 30 employees. The office currently uses a single LAN where all devices (designers' workstations, administration PCs, guest Wi-Fi devices, and a central NAS server holding client intellectual property) are connected via the same network switches without physical or logical isolation. Recently, an unauthorized guest connected to the office Wi-Fi and was able to view sensitive financial spreadsheets on an administrative PC. Part (a): Identify two security vulnerabilities present in PixelCraft's current network design. [2 marks] Part (b): Explain how the implementation of Virtual Local Area Networks (VLANs) could mitigate the risk of unauthorized access from guest devices. [4 marks] Part (c): Describe how the network administrator could use a combination of MAC address filtering and a firewall to restrict access to the central NAS server. [5 marks] Part (d): PixelCraft plans to allow designers to work from home. Explain the role of encryption and tunneling when utilizing a Virtual Private Network (VPN) to access office resources securely over the Internet. [4 marks]
PastPaper.showAnswers

PastPaper.workedSolution

Part (a): (1) Lack of network segmentation allows any connected device (including guests) to broadcast and communicate directly with administrative hosts. (2) Unsecured or poorly authenticated wireless access points provide guests full entry to the local intranet. Part (b): (1) VLANs logically segment the physical LAN into multiple distinct broadcast domains (e.g., Guest VLAN, Admin VLAN). (2) Devices on different VLANs cannot communicate at Layer 2, preventing accidental discovery. (3) Any communication between VLANs must be routed through a Layer 3 device (router or multilayer switch). (4) The network administrator can configure Access Control Lists (ACLs) on the router to block all traffic attempting to cross from the Guest VLAN to other private VLANs. Part (c): (1) MAC address filtering works at the Data Link Layer (Layer 2) to permit network access only to specific registered physical interfaces. (2) This prevents unauthorized or spoofed devices from connecting to the switch ports or wireless access points. (3) However, MAC addresses can be easily spoofed, meaning it is not sufficient on its own. (4) A firewall acts at Layer 3 and above to inspect traffic packets based on IP addresses, ports, and protocols. (5) In tandem, MAC filtering prevents physical-level unauthorized attachment, while the firewall applies policy-level rules (e.g., blocking non-admin IPs or protocols like SMB from accessing the NAS), creating a strong defense-in-depth scheme. Part (d): (1) Tunneling encapsulates private network packets inside public network transit packets. (2) This enables local private protocols to safely cross the public Internet structure to reach the office server. (3) Encryption translates the contents of these packets into unreadable ciphertext using cryptographic algorithms. (4) This protects data confidentiality, ensuring that any intercepted data remains secure from sniffing or man-in-the-middle attacks.

PastPaper.markingScheme

Part (a): Award [1] mark for each correctly identified network vulnerability up to [2]. Part (b): Award [1] mark for each logical step explained in VLAN implementation up to [4] (segmentation, lack of Layer 2 traversal, router/Layer 3 intervention, and ACL application). Part (c): Award [1] mark for each point explaining MAC filtering, its vulnerability, firewall operations, and the combined defense-in-depth effectiveness up to [5]. Part (d): Award [1] mark for each clear point explaining encapsulation (tunneling), routing, security translation (encryption), and confidentiality benefits up to [4].
PastPaper.question 3 · Pseudocode Algorithm construction
13 PastPaper.marks
A logistics company manages a smart distribution center containing 8 loading zones, with each zone containing 12 docks. The status of each dock is monitored and stored in a global two-dimensional array of strings called DOCKS, where DOCKS[Z][D] represents the status of dock D (0 to 11) in loading zone Z (0 to 7).

The status of a dock can be "EMPTY", "LOADING", or "MAINTENANCE".

An automated system needs to assign incoming trucks to a loading zone. To maximize efficiency, trucks should be sent to a loading zone that meets the following criteria:
1. It must contain NO docks currently under "MAINTENANCE".
2. It must have the highest number of "EMPTY" docks (which must be at least 1).

If there is a tie between multiple loading zones, the zone with the lowest index (closest to the main entrance) should be selected. If no loading zone meets the criteria, the system should output -1.

(a) Describe one advantage of using a two-dimensional array rather than multiple one-dimensional arrays to represent this system. [3 marks]

(b) Construct a pseudocode algorithm for the procedure findBestZone() that scans the DOCKS array, applies the criteria above, and outputs the index of the best loading zone, or -1 if no suitable zone is found. [10 marks]
PastPaper.showAnswers

PastPaper.workedSolution

Part (a) Solution:
Using a single 2D array is highly beneficial because:
1. Better organization: It groups all zone and dock data logically under one data structure rather than requiring 8 separate variables.
2. Iteration simplicity: It enables the use of nested loops with index variables (Z and D) to process all elements dynamically. To add new zones or docks, only the bounds of the loops need adjustment.
3. Maintainability: Minimizes code complexity and makes modifications straightforward.

Part (b) Solution:
- Initialize global tracker variable for best zone index to -1.
- Initialize global tracker variable for highest empty count to 0 (ensures that a zone must have at least 1 empty dock to be selected over -1).
- Use an outer loop to iterate through each zone (0 to 7).
- For each zone, set a boolean flag (e.g., HAS_MAINTENANCE) to false, and a local counter (e.g., EMPTY_COUNT) to 0.
- Use an inner loop to check each dock (0 to 11) in that zone.
- If a dock is under MAINTENANCE, flag the zone as invalid.
- If a dock is EMPTY, increment the empty counter.
- After checking all docks in a zone, verify if the maintenance flag is still false.
- If false, compare the zone's EMPTY_COUNT to the running MAX_EMPTY. If strictly greater (>), update MAX_EMPTY and store the current zone index Z in BEST_ZONE (using > instead of >= preserves the lower index in the event of a tie).
- After checking all zones, output the BEST_ZONE.

PastPaper.markingScheme

Part (a) [3 marks]
- 1 mark: Identifies an advantage (e.g., easier implementation using nested loops, single named variable to represent the grid).
- 1 mark: Elaborates on the mechanism (e.g., avoids having to name and query 8 independent 1D arrays individually).
- 1 mark: Connects clearly to the scenario (e.g., facilitates scaling up the number of loading zones or docks by simply modifying array dimensions).

Part (b) [10 marks]
- 1 mark: Correctly initializes the tracking variables (BEST_ZONE = -1 and MAX_EMPTY = 0).
- 1 mark: Sets up outer loop correctly from 0 to 7 to scan all zones.
- 1 mark: Sets up inner loop correctly from 0 to 11 to scan all docks.
- 1 mark: Correctly initializes checking variables (HAS_MAINTENANCE = false and EMPTY_COUNT = 0) at the start of each zone's iteration.
- 1 mark: Checks for the condition "MAINTENANCE" and updates the boolean flag accordingly.
- 1 mark: Checks for the condition "EMPTY" and increments the local count of empty docks.
- 1 mark: Checks if the current zone contains no maintenance docks after the inner loop finishes.
- 1 mark: Compares the current zone's empty dock count with the maximum found so far using a strict inequality (>) to preserve the lowest index during a tie.
- 1 mark: Correctly updates the running maximum (MAX_EMPTY) and the best zone index (BEST_ZONE) when a better zone is found.
- 1 mark: Outputs or returns the final BEST_ZONE after all loops have executed.

Paper 2 Option D (OOP)

Answer all questions from the OOP option. Java syntax, design, UML diagrams, and class implementation.
3 PastPaper.question · 45 PastPaper.marks
PastPaper.question 1 · practical
17 PastPaper.marks
A fitness tracking application manages information about different physical workouts.

(a) Define the term encapsulation and state one advantage of using encapsulation in the design of the classes for this application. [2]

(b) Draw a UML class diagram for the Workout class. The class contains:
- private fields: workoutID (String), duration (integer, in minutes), and caloriesBurned (double).
- public methods: a constructor that sets all three fields, a getter method for duration, and a method addCalories(double cal) that increases the calories burned. [3]

(c) Outline the purpose of a constructor in Java, and explain how constructor overloading could be used to initialize a Workout object when the calories burned are not yet known. [3]

(d) Construct the Java class definition for the Workout class. The method addCalories(double cal) must ensure that calories are only added if the parameter cal is greater than 0. [5]

(e) The developers decide to create a subclass called CardioWorkout that extends Workout. Distinguish between a superclass and a subclass, and describe how the super keyword is used in the subclass constructor to pass parameters to the parent class. [4]
PastPaper.showAnswers

PastPaper.workedSolution

Part (a)
- Encapsulation is the OOP practice of wrapping data (attributes) and methods that act on that data into a single unit (class), while restricting direct access to the internal state by making fields private.
- Advantage: It protects the integrity of the data. For example, external code cannot directly alter caloriesBurned to a negative number; any modification must go through the addCalories method which can validate input.

Part (b)
------------------------------------------------
| Workout |
------------------------------------------------
| - workoutID : String |
| - duration : int |
| - caloriesBurned : double |
------------------------------------------------
| + Workout(workoutID: String, duration: int, |
| caloriesBurned: double) |
| + getDuration() : int |
| + addCalories(cal: double) : void |
------------------------------------------------

Part (c)
- A constructor is a special block of code that is executed when an instance of an object is created to initialize its state (assign initial values to its instance variables).
- Constructor overloading allows defining multiple constructors with different parameter lists. For this application, a second constructor could be defined with only workoutID and duration as parameters, which automatically sets caloriesBurned to 0.0. This provides flexibility during instantiation when calorie data is not yet available.

Part (d)
public class Workout {
private String workoutID;
private int duration;
private double caloriesBurned;

public Workout(String workoutID, int duration, double caloriesBurned) {
this.workoutID = workoutID;
this.duration = duration;
this.caloriesBurned = caloriesBurned;
}

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

public void addCalories(double cal) {
if (cal > 0) {
this.caloriesBurned += cal;
}
}
}

Part (e)
- A superclass is a parent class that defines common attributes and behaviors that can be inherited by other classes.
- A subclass is a child class that inherits all state and behavior from the superclass and can add specific attributes, unique methods, or override inherited methods.
- The 'super' keyword: Inside the subclass constructor, 'super' is invoked with arguments (e.g., super(workoutID, duration, caloriesBurned)) to call the superclass's constructor.
- This call must be the very first statement in the subclass constructor to ensure the parent class fields are properly initialized before any subclass initialization occurs.

PastPaper.markingScheme

Part (a) [2 marks]
- [1 mark] for a complete definition of encapsulation (mentioning data hiding / private fields combined with public methods).
- [1 mark] for explaining a valid advantage relevant to the context (e.g., security, data integrity, validation).

Part (b) [3 marks]
- [1 mark] for correct class name and visibility modifiers (- for private, + for public) on all elements.
- [1 mark] for correct fields with their respective data types.
- [1 mark] for correct methods, parameter lists, and return types (or void).

Part (c) [3 marks]
- [1 mark] for outlining the main purpose of a constructor (initialization of object state/fields).
- [1 mark] for defining constructor overloading (same name, different parameter lists).
- [1 mark] for explaining how it applies to the workout scenario (e.g., creating a constructor with fewer arguments that sets default/zero values for calories).

Part (d) [5 marks]
- [1 mark] for correct class declaration and declaring three private attributes with matching types.
- [1 mark] for correct public constructor with three parameters and assigning them using 'this' appropriately.
- [1 mark] for correct accessor method getDuration() returning an integer.
- [1 mark] for correct method header for addCalories(double cal) returning void.
- [1 mark] for validation logic (if cal > 0) and updating caloriesBurned correctly.

Part (e) [4 marks]
- [1 mark] for distinguishing the role of a superclass.
- [1 mark] for distinguishing the role of a subclass.
- [1 mark] for explaining that 'super' is used to call the parent constructor and pass relevant parameters.
- [1 mark] for noting that 'super' must be the first line of code inside the subclass constructor.
PastPaper.question 2 · OOP Practical & Theory
9 PastPaper.marks
An application is designed to track athletic performances using Java.

(a) Describe the difference between a primitive data type (such as double) and an object reference in Java, in terms of how they are stored in memory. [2 marks]

The class Competitor is defined below:

public class Competitor {
private int id;
private double score;

public Competitor(int id, double score) {
this.id = id;
this.score = score;
}

public double getScore() {
return this.score;
}
}

(b) Construct the method public static void sortCompetitors(Competitor[] list) that sorts the array in-place in descending order of the competitors' scores, using either a selection sort or a bubble sort algorithm. [7 marks]
PastPaper.showAnswers

PastPaper.workedSolution

Part (a)
- Primitive data types hold the actual value (e.g., the double value) directly in the variable's allocated stack memory.
- Reference variables hold the memory address (reference) that points to the location on the heap where the object actually exists.

Part (b)
Selection Sort Solution:
```java
public static void sortCompetitors(Competitor[] list) {
for (int i = 0; i < list.length - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (list[j].getScore() > list[maxIndex].getScore()) {
maxIndex = j;
}
}
Competitor temp = list[maxIndex];
list[maxIndex] = list[i];
list[i] = temp;
}
}
```

Bubble Sort Alternative Solution:
```java
public static void sortCompetitors(Competitor[] list) {
int n = list.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (list[j].getScore() < list[j + 1].getScore()) {
Competitor temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
```

PastPaper.markingScheme

Part (a) [2 marks]
- 1 mark for describing that primitive data types store the actual numeric or boolean values directly in stack memory.
- 1 mark for describing that an object reference stores a memory address/pointer pointing to an object residing on the heap.

Part (b) [7 marks]
- 1 mark: Correct outer loop header (initializing index, correct termination condition to prevent array boundary errors).
- 1 mark: Correct inner loop header (relative to outer index if using selection sort, or relative to outer index and array bounds if using bubble sort).
- 1 mark: Correctly invoking the `getScore()` accessor method on the array elements.
- 1 mark: Correct comparison check for descending order (e.g. tracking index of higher value in selection sort, or swapping adjacent elements if left < right in bubble sort).
- 1 mark: Declaring a temporary variable of type `Competitor`.
- 1 mark: Correct three-way swap algorithm logic using the temporary variable.
- 1 mark: Correct overall method signature matching the specification (public static void, correct array parameter name and type).
PastPaper.question 3 · long answer
19 PastPaper.marks
An events management company is developing a Java program to manage registrations for an upcoming international technology conference.

The system involves three classes: Conference, Session, and Attendee.
- Attendee stores personal details (name, email) and ticket type ("VIP" or "Standard").
- Session represents a specific seminar, holding an array of registered Attendee objects up to a certain capacity.
- Conference acts as the coordinator, containing an array of all scheduled Session objects.

(a) Describe the relationship (including multiplicity) between Conference, Session, and Attendee, and construct a text-based UML diagram representing these classes and their relationships. [3]

(b) Explain how encapsulation is achieved in the Attendee class and outline one advantage this provides to the development of the larger conference management system. [4]

(c) Write the complete Java class definition for Session, including its instance variables (sessionID, title, maxCapacity, registeredAttendees (an array of Attendee), and currentCount) and its constructor. The constructor should accept sessionID, title, and maxCapacity as parameters and initialize the array appropriately. [4]

(d) Implement the method registerAttendee(Attendee target) in Java for the Session class. The method should attempt to add target to the registeredAttendees array. An attendee can only be registered if:
- The session is not full (i.e., currentCount is less than maxCapacity).
- The attendee is not already registered in this session (checked using the email field via a getter method getEmail() on the Attendee class).

The method should update currentCount, insert the attendee, and return true if registration is successful, and false otherwise. [8]
PastPaper.showAnswers

PastPaper.workedSolution

Part (a)
- Relationship between Conference and Session: One-to-many (1 to *). A Conference contains 1 or more Session objects, whereas a Session belongs to exactly one Conference.
- Relationship between Session and Attendee: Many-to-many (or 1-to-many in terms of the Session's aggregation of Attendee). A Session aggregates 0 to maxCapacity Attendee objects, and an Attendee can register for 0 or more Session objects.

UML Diagram:
+--------------+ +-----------+ +----------+
| Conference | 1 * | Session | 1 * | Attendee |
|--------------|--------->|-----------|--------->|----------|
| | | | | |
+--------------+ +-----------+ +----------+

Part (b)
- How encapsulation is achieved:
Declaring the variables of the Attendee class (such as name, email, ticketType) as private, and exposing them only through controlled public getter and setter methods (e.g., getName(), getEmail()).
- Advantage:
Data Protection/Control: It prevents unauthorized direct modifications to sensitive student/attendee information (such as arbitrarily upgrading a ticketType to 'VIP' without validation). It also decouples the interface from the internal representation, meaning the internal implementation of Attendee can change without affecting how Session or Conference interacts with it.

Part (c)
```java
public class Session {
private String sessionID;
private String title;
private int maxCapacity;
private Attendee[] registeredAttendees;
private int currentCount;

public Session(String sessionID, String title, int maxCapacity) {
this.sessionID = sessionID;
this.title = title;
this.maxCapacity = maxCapacity;
this.registeredAttendees = new Attendee[maxCapacity];
this.currentCount = 0;
}
}
```

Part (d)
```java
public boolean registerAttendee(Attendee target) {
if (this.currentCount >= this.maxCapacity) {
return false;
}
for (int i = 0; i < this.currentCount; i++) {
if (this.registeredAttendees[i].getEmail().equals(target.getEmail())) {
return false;
}
}
this.registeredAttendees[this.currentCount] = target;
this.currentCount++;
return true;
}
```

PastPaper.markingScheme

Part (a) [3 Marks]
- 1 mark: Describing the relationship between Conference and Session with correct multiplicity (1 to many).
- 1 mark: Describing the relationship between Session and Attendee with correct multiplicity (1/many to many).
- 1 mark: A correct representation in a text-based UML diagram showing aggregation/association with correct direction/multiplicity.

Part (b) [4 Marks]
- 1 mark: Explicitly stating that variables are declared as private.
- 1 mark: Stating that public getter/setter methods are used to access/modify them.
- 1 mark: Identifying a concrete advantage (e.g., validation of ticketType, data security, code maintenance).
- 1 mark: Expanding on the advantage in the context of the conference system (e.g., prevents bypassing payment/verification).

Part (c) [4 Marks]
- 1 mark: Correct access modifiers and data types for all five instance variables.
- 1 mark: Correct constructor header with three parameters.
- 1 mark: Correct assignment of parameters to instance variables using 'this'.
- 1 mark: Correctly instantiating the array using 'new Attendee[maxCapacity]' and setting 'currentCount' to 0.

Part (d) [8 Marks]
- 1 mark: Correct method header: public boolean registerAttendee(Attendee target).
- 1 mark: Checking if the session is full (currentCount >= maxCapacity) and returning false.
- 2 marks: Correctly looping through the array up to currentCount (Award 1 mark if looping up to maxCapacity but with a null check to avoid NullPointerException).
- 2 marks: Correctly comparing email addresses using target.getEmail() and .equals() (or equivalent comparison) and returning false if a duplicate is found.
- 1 mark: Adding the target attendee to the array at index currentCount.
- 1 mark: Correctly incrementing currentCount and returning true.

PastPaper.sampleCTATitle

PastPaper.sampleCTADescription

PastPaper.sampleStickyMessage

PastPaper.stickyCtaText