Understand Fundamentals of Programming — Questions and Answers
CDACC Level 6 • March/April 2026 written assessment.
Work through each question before reading the answer. These worked revision answers are prepared for Jemshah learners; they are not an official marking scheme.
Question 1
Programming languages undergo several phases during development. List FOUR phases of program development in their correct sequence. (4 marks)
Answer
- Analyse and define the problem and requirements.
- Design the algorithm, data and program structure.
- Code/implement the program.
- Test and debug it against the requirements.
Question 2
Write Java statements to declare variables for storing a student’s registration number (as text), age (as whole number), and average score (as decimal number). (3 marks)
Answer
String registrationNumber;
int age;
double averageScore;
Question 3
The Java Development Kit (JDK) provides various tools for developing Java applications. Explain TWO JDK tools used in program development. (4 marks)
Answer
javacis the Java compiler: it translates Java source files into JVM bytecode class files.javalaunches the JVM and runs a compiled Java application.
Question 4
A trainee software developer attempted to write a simple Java program to calculate and display the product of a number and 5. Identify THREE syntax errors in the following Java program that prevent it from executing correctly: Public class student { public static void main(String[] args) { int 1stNumber = 50; int result = 1stNumber * 5 System.out.println(result); } } (3 marks)
Answer
- Java keywords are case-sensitive:
Publicmust bepublic. - An identifier cannot begin with a digit: rename
1stNumbertofirstNumberin both places. - The statement
int result = firstNumber * 5needs a terminating semicolon.
Corrected program, saved as student.java:
public class student {
public static void main(String[] args) {
int firstNumber = 50;
int result = firstNumber * 5;
System.out.println(result);
}
}
Output: 250. A lowercase class name is allowed, although an initial capital is the usual naming convention.
Question 5
State the difference between private and public access specifiers, providing an example of when each would be appropriately used. (4 marks)
Answer
private restricts access to the declaring class (subject to Java’s enclosing/nested-class access rules); use it for a bank account’s balance so outside code cannot alter the field directly. public permits access from other classes where the declaring type/module is accessible; use it for a method such as getBalance() that is part of the class’s intended interface.
Question 6
Outline a Java program segment that declares a String variable called studentName, assigns it the value “John Doe”, then uses TWO different String methods to: Display the length of the name Convert the name to lowercase (4 marks)
Answer
String studentName = "John Doe";
System.out.println(studentName.length());
System.out.println(studentName.toLowerCase());
Output: 8, then john doe. The space counts as one character.
Question 7
Operators in Java are classified based on the number of operands they operate on. Distinguish between unary and binary operators by providing ONE example of each with its operation. (4 marks)
Answer
A unary operator acts on one operand: ++count increases count by one. A binary operator acts on two operands: a + b adds the values of a and b.
Question 8
A trainee programmer is testing decision-making logic in a Java application that compares student scores stored in variables. Determine the output of the following Boolean expressions that is being tested: int x = 15; int y = 20; int z = 15; boolean outcome1 = (x == z); boolean outcome2 = (x > y); boolean outcome3 = (x <= y) && (y > z); boolean outcome4 = (x != z) || (y < z); (4 marks)
Answer
outcome1 = true: x and z are both 15.outcome2 = false: 15 is not greater than 20.outcome3 = true: 15 ≤ 20 and 20 > 15 are both true.outcome4 = false: 15 ≠ 15 is false and 20 < 15 is false; false OR false is false.
Question 9
Loops enable repetitive execution of code blocks . Write a Java program segment using a while loop to display even numbers from 2 to 20. (4 marks)
Answer
int number = 2;
while (number <= 20) {
System.out.println(number);
number += 2;
}
Output: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, each on its own line.
Question 10
Exception handling improves program robustness. Explain the purpose of try, catch, and finally blocks in Java exception handling. (3 marks)
Answer
trycontains code whose exceptions are being handled.catchhandles an exception of its specified type if one is thrown from the associated try block.finallyruns after the try/catch in normal execution whether an exception occurs or not, and is used for cleanup. It is not guaranteed after forced JVM termination.
Question 11
Write a Java program segment that creates an array called temperatures containing five integer values: 23, 25, 28, 22, 26. The program should calculate and display the average temperature. (3 marks)
Answer
int[] temperatures = {23, 25, 28, 22, 26};
int sum = 0;
for (int temperature : temperatures) {
sum += temperature;
}
double average = (double) sum / temperatures.length;
System.out.println(average);
Sum = 124; average = 124/5 = 24.8. Casting to double prevents integer division.
Average temperature
- Formula: average = sum of temperatures ÷ number of temperatures.
- Add the values: 23 + 25 = 48; 48 + 28 = 76; 76 + 22 = 98; 98 + 26 = 124.
- There are 5 temperatures.
- Substitute: average = 124 ÷ 5.
- Final answer: 24.8 temperature units. The paper does not specify °C or °F.
- The Java cast (double) sum ensures decimal division.
Question 12
a. Algorithm design is fundamental to problem-solving in programming. i. Define the term algorithm as used in programming. (2 marks) ii. A teacher wants to calculate the average of three test scores and determine if a student has passed (average ≥ 50). Design a flowchart to represent this algorithm. (6 marks) iii. Convert the flowchart in (ii) above into a complete Java program that accepts three scores from the keyboard and displays both the average and pass/fail status. (6 marks) b. Object-oriented programming utilizes specific principles to structure code effectively. Explain TWO principles of object-oriented programming: Abstraction and Polymorphism, providing a practical example for each. (6 marks)
Answer
(a)(i) An algorithm is a finite, ordered sequence of unambiguous steps for solving a problem or producing a required result.
(a)(ii) Flowchart

(a)(iii) Save as AverageResult.java:
import java.util.Scanner;
public class AverageResult {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter three scores: ");
double score1 = input.nextDouble();
double score2 = input.nextDouble();
double score3 = input.nextDouble();
double average = (score1 + score2 + score3) / 3.0;
System.out.printf("Average: %.2f%n", average);
System.out.println(average >= 50 ? "Pass" : "Fail");
input.close();
}
}
For scores 40, 50 and 60, the average is 50.00 and the output is Pass; the comparison includes exactly 50.
(b) Abstraction exposes essential operations while hiding implementation details. For example, calling account.deposit(2000) uses an interface without needing to know how account data is stored. Polymorphism permits a superclass/interface reference to refer to different concrete objects whose overridden methods behave differently. For example, an Employee reference to a Manager invokes the manager’s overridden displayInfo().
Average of three example scores
- Example inputs: 40, 50 and 60.
- Formula: average = (score1 + score2 + score3) ÷ 3.
- Substitute: average = (40 + 50 + 60) ÷ 3.
- Sum = 150; average = 150 ÷ 3 = 50.00.
- Compare with the pass condition: 50.00 ≥ 50 is true.
- Final status: Pass. An average below 50 gives Fail.
Question 13
a. A supermarket needs a program to calculate the total cost of items purchased. Develop a complete Java program that: Prompts the user to enter the item name, unit price, and quantity Calculates the subtotal (price × quantity) Applies a 10% discount if the subtotal exceeds Ksh. 5000 Calculates and displays: item name, subtotal, discount amount, and final amount to pay Use appropriate data types and include proper output formatting. (10 marks) b. Control structures determine the flow of program execution. Compare the use of if-else statements and switch-case statements, highlighting TWO advantages of each. (4 marks) c. Construct a Java program using a for loop to display the multiplication table of 7 from 7×1 to 7×12 in the format: 7 x 1 = 7 7 x 2 = 14 … (6 marks)
Answer
(a) Save as SupermarketBill.java:
import java.util.Scanner;
public class SupermarketBill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Item name: ");
String itemName = input.nextLine();
System.out.print("Unit price: ");
double unitPrice = input.nextDouble();
System.out.print("Quantity: ");
int quantity = input.nextInt();
double subtotal = unitPrice * quantity;
double discount = subtotal > 5000 ? 0.10 * subtotal : 0.0;
double amountToPay = subtotal - discount;
System.out.printf("Item: %s%nSubtotal: Ksh %.2f%n", itemName, subtotal);
System.out.printf("Discount: Ksh %.2f%nAmount to pay: Ksh %.2f%n",
discount, amountToPay);
input.close();
}
}
Example: unit price 1200 and quantity 5 give subtotal Ksh 6000.00, discount Ksh 600.00 and final amount Ksh 5400.00. A subtotal of exactly Ksh 5000 receives no discount because the question says “exceeds”.
(b) An if-else handles general Boolean conditions and ranges (such as score ≥ 50), and can combine multiple conditions. A switch groups discrete alternatives for one selector clearly and avoids repeating a long chain of equality comparisons. Choose if-else for ranges/compound tests and switch for a clear set of discrete cases.
(c)
for (int i = 1; i <= 12; i++) {
System.out.println("7 x " + i + " = " + (7 * i));
}
Supermarket bill
- Example: unit price = KSh 1,200; quantity = 5.
- Subtotal formula: unit price × quantity.
- Subtotal = 1,200 × 5 = KSh 6,000.
- Since 6,000 > 5,000, the 10% discount applies.
- Discount = 10 ÷ 100 × 6,000 = KSh 600.
- Amount to pay = subtotal − discount = 6,000 − 600.
- Final amount = KSh 5,400. A subtotal of exactly KSh 5,000 receives no discount.
Question 14
a. Classes and objects are fundamental concepts in Java programming. i. Show the difference between a class and an object, using a real-world analogy to illustrate your explanation. (4 marks) ii. Create a Java class called BankAccount with the following specifications: Private data members: accountNumber (String), balance (double) A constructor to initialize both data members A method called deposit() that accepts an amount and adds it to the balance A method called getBalance() that returns the current balance Demonstrate the creation of an object with account number “ACC001” and initial balance 5000, then deposit 2000 and display the final balance (12 marks) b. Methods enhance code reusability and organization. Explain the difference between methods with return values and void methods, providing a Java code example of each. (4 marks)
Answer
(a)(i) A class defines fields and behaviour, like a blueprint for a house. An object is one created instance of that class, like an actual house constructed from the blueprint; different objects can hold different field values.
(a)(ii) Save as BankAccount.java:
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balance += amount;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount("ACC001", 5000);
account.deposit(2000);
System.out.printf("Final balance: %.2f%n", account.getBalance());
}
}
Output: Final balance: 7000.00.
(b) A value-returning method declares a result type and returns a compatible result. A void method performs an action without returning a value:
static int add(int a, int b) {
return a + b;
}
static void displayMessage(String message) {
System.out.println(message);
}
Account balance
- Opening balance = KSh 5,000.
- Deposit = KSh 2,000.
- New balance formula: opening balance + deposit.
- New balance = 5,000 + 2,000.
- Final balance = KSh 7,000.00.
Question 15
a. Inheritance is a key feature of object-oriented programming that promotes code reuse. Illustrate the concept of inheritance by creating: A parent class called Employee with attributes: name (String) and salary (double), including a constructor and a method displayInfo() to print employee details A child class called Manager that inherits from Employee and adds an attribute department (String), with its own constructor and an overridden displayInfo() method Create an object of the Manager class with name “Alice Smith”, salary 80000, and department “IT”, then display the information (12 marks) b. Method overloading allows multiple methods with the same name but different parameters. Demonstrate method overloading by creating THREE methods called calculateArea() that: Calculate the area of a square (one parameter: side) Calculate the area of a rectangle (two parameters: length and width) Calculate the area of a circle (one parameter: radius, use π = 3.14159) Include the method declarations and sample method calls. (8 marks)
Answer
(a) Save the following together as InheritanceDemo.java:
class Employee {
protected String name;
protected double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public void displayInfo() {
System.out.printf("Name: %s%nSalary: %.2f%n", name, salary);
}
}
class Manager extends Employee {
private String department;
public Manager(String name, double salary, String department) {
super(name, salary);
this.department = department;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Department: " + department);
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Manager manager = new Manager("Alice Smith", 80000, "IT");
manager.displayInfo();
}
}
Output identifies Alice Smith, salary 80000.00 and department IT. extends Employee creates the inheritance relationship; super(...) initialises the parent fields and @Override identifies the replaced implementation.
(b) Square and circle methods cannot both use the signature calculateArea(double); changing a parameter name or a return type does not create an overload. This valid answer uses an integer side for the square and a double radius for the circle, and two doubles for the rectangle:
public class AreaDemo {
static int calculateArea(int side) {
return side * side;
}
static double calculateArea(double length, double width) {
return length * width;
}
static double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
public static void main(String[] args) {
System.out.println("Square: " + calculateArea(5));
System.out.println("Rectangle: " + calculateArea(5.0, 4.0));
System.out.println("Circle: " + calculateArea(3.0));
}
}
The calls produce 25, 20.0 and 28.27431 respectively. Writing calculateArea(5.0) selects the circle overload; the intended shape therefore depends on the argument type in this design.
Area examples
- Square: A = side². With side 5, A = 5 × 5 = 25 square units.
- Rectangle: A = length × width. With length 5 and width 4, A = 5 × 4 = 20 square units.
- Circle: A = πr². Use the paper’s π = 3.14159 and radius 3.
- r² = 3 × 3 = 9.
- Circle area = 3.14159 × 9 = 28.27431 square units.
- Method signatures differ by parameter number/type: int for the square, double for the circle, two doubles for the rectangle.