QUESTION ONE (20 MARKS) – COMPULSORY
a) Explain the following terms as used in JAVA programming.
i) Character stream (2 marks)
A character stream is used in Java to handle input and output of text data
(characters). It processes data in 16-bit Unicode format.
Examples include FileReader and FileWriter.
ii) Thread (2 marks)
A thread is a lightweight unit of execution that allows a program to perform
multiple tasks concurrently (multithreading).
iii) IDE (2 marks)
An Integrated Development Environment (IDE) is a software tool used to write,
compile, debug, and run programs.
Examples: Eclipse, NetBeans, IntelliJ IDEA.
b) Construct a switch statement with a suitable default case for the input
below so as to generate the specified output: (4 marks)
Input → Output
S → “Single”
M → “Married”
D → “Divorced”
Answer:
char input = 'S';
switch(input) {
case 'S':
[Link]("Single");
break;
case 'M':
[Link]("Married");
break;
case 'D':
[Link]("Divorced");
break;
default:
[Link]("Invalid input");
}
c) A student read a program and found some access specifiers in it. Highlight
their uses
i) Public (2 marks)
Accessible from any other class anywhere in the program.
ii) Private (2 marks)
Accessible only within the class where it is declared.
iii) Protected (2 marks)
Accessible within the same package and also in subclasses (even if they are in
different packages).
d) Using suitable examples distinguish between error and exceptions. (2
marks)
Error: A serious problem that cannot be handled (e.g., OutOfMemoryError).
Exception: A problem that can be handled using try-catch (e.g.,
ArithmeticException).
Example:
int x = 10 / 0; // Causes ArithmeticException
e) List two methods of flow control in JAVA. (2 marks)
1. Selection statements (if, if-else, switch)
2. Iteration statements (for, while, do-while)
✅ QUESTION TWO (15 MARKS)
a) Using a suitable java code, show how java handles exception using blocks (4
marks)
Answer:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} finally {
[Link]("Execution completed");
}
b) Using suitable code examples highlight two methods of concatenating text
in JAVA programming. (4 Marks)
1. Using + operator
String name = "John";
[Link]("Hello " + name);
2. Using concat() method
String str1 = "Hello ";
String str2 = "World";
[Link]([Link](str2));
c) Consider a JFrame form shown below.
(From page 2, the diagram shows fields: Cats, Exams, Total, Grade and a Save
button.)
The user inputs coursework (cats) and exam marks. The system calculates total and
assigns grade based on:
Total Marks Grade
≥70 A
60–69 B
50–59 C
40–49 D
<40 E
i. Write Java Skeleton code to calculate total marks (2 marks)
int cats = [Link]([Link]());
int exams = [Link]([Link]());
int total = cats + exams;
[Link]([Link](total));
ii. Write Java Skeleton code to calculate the grade (5 marks)
int total = [Link]([Link]());
String grade;
if (total >= 70) {
grade = "A";
} else if (total >= 60) {
grade = "B";
} else if (total >= 50) {
grade = "C";
} else if (total >= 40) {
grade = "D";
} else {
grade = "E";
}
[Link](grade);
✅ QUESTION THREE (15 MARKS)
a) Explain the output from the following JAVA bit wise operations
i. 9 ^ 5 (3 marks)
9 = 1001
5 = 0101
Result = 1100 = 12
ii. 7 << 3 (3 marks)
7 = 00000111
Shift left 3 times → 00111000 = 56
b) Explain the following types of casting as used in JAVA programming
i. int myInt = 9; double myDouble = myInt; (2 marks)
This is implicit casting (widening). Java automatically converts int to double.
ii. double myDouble = 9.78d; int myInt = (int) myDouble; (2 marks)
This is explicit casting (narrowing). Manual conversion; decimal part is lost.
c) Using a suitable diagram describe clearly the Java architecture (5 marks)
Answer:
Java architecture consists of:
Source Code (.java)
Compiler (javac)
Bytecode (.class)
JVM (Java Virtual Machine)
Output
Flow:
Source Code → Compiler → Bytecode → JVM → Output
✅ QUESTION FOUR (15 MARKS)
i) List the two types of polymorphism (2 marks)
1. Compile-time polymorphism (Method Overloading)
2. Runtime polymorphism (Method Overriding)
ii) Using suitable program code implement the polymorphism discussed above
(6 marks)
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal obj = new Dog();
[Link]();
}
}
b) James a student in KCA university wanted to create a program using JAVA
programming language. Justify using two points his choice JAVA over others.
(4 marks)
1. Platform independent (Write once, run anywhere)
2. Secure and robust (automatic memory management, no pointers)
c) Highlight three tools for creating GUI programs in JAVA. (3 marks)
1. Swing
2. AWT (Abstract Window Toolkit)
3. JavaFX
JAVA PROGRAMMING EXAM – ANSWERS (2024/2025)
✅ QUESTION ONE (COMPULSORY – 20 MARKS)
a) Compare Procedural Programming and Object-Oriented Programming
paradigms. Discuss at least three major differences with concrete examples. (4
marks)
Answer:
Procedural Programming Object-Oriented Programming
Focuses on functions/procedures Focuses on objects/classes
Data and functions are separate Data and methods are bundled (encapsulation)
Top-down approach Bottom-up approach
Procedural Programming Object-Oriented Programming
Less secure (global data) More secure (data hiding)
Example:
Procedural: C program using functions
OOP: Java program using classes and objects
b) Write a Java class Product with the following attributes: name, price, and
quantity. Include:
i. A constructor for initializing all fields
ii. A method calculateTotalValue() that returns the total value of the product (price
× quantity)
iii. A method displayInfo() that prints all product details (4 marks)
Answer:
class Product {
String name;
double price;
int quantity;
// Constructor
Product(String name, double price, int quantity) {
[Link] = name;
[Link] = price;
[Link] = quantity;
}
// Calculate total value
double calculateTotalValue() {
return price * quantity;
}
// Display product info
void displayInfo() {
[Link]("Name: " + name);
[Link]("Price: " + price);
[Link]("Quantity: " + quantity);
[Link]("Total Value: " + calculateTotalValue());
}
}
c) Explain the difference between checked and unchecked exceptions in Java.
Give two examples of each. (3 marks)
Answer:
Checked Exceptions:
Must be handled at compile time using try-catch or throws.
Examples: IOException, SQLException
Unchecked Exceptions:
Occur at runtime and are not checked at compile time.
Examples: NullPointerException, ArithmeticException
d) You are developing a Java program that reads customer reviews from a text
file named [Link] and writes the word APPROVED to another file named
[Link].
Write the code for this file reading and writing operation using proper exception
handling. (4 marks)
Answer:
import [Link].*;
public class FileExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new
FileReader("[Link]"));
BufferedWriter writer = new BufferedWriter(new FileWriter("[Link]"));
String line;
while ((line = [Link]()) != null) {
// Process review (optional)
}
[Link]("APPROVED");
[Link]();
[Link]();
} catch (IOException e) {
[Link]("Error handling file: " + [Link]());
}
}
}
e) With reference to polymorphism in Java:
i. Explain the difference between method overloading and method overriding
Answer:
Method Overloading: Same method name, different parameters (compile-
time)
Method Overriding: Same method in subclass with same signature
(runtime)
ii. Provide one real-world analogy for each (5 marks)
Answer:
Overloading analogy: A person with the same name but different roles
(e.g., “John” as a teacher and “John” as a driver).
Overriding analogy: A child inheriting behavior from a parent but changing
it (e.g., a child speaks differently than the parent).
✅ QUESTION TWO (15 MARKS)
a) A university wants to calculate results for 5 students. Each student has 3
subjects. Using a 2D array, write a Java program that:
i. Accepts all marks from the user
ii. Calculates and prints each student’s average
iii. Displays the overall average for the class (7 marks)
Answer:
import [Link];
public class StudentMarks {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[][] marks = new int[5][3];
double total = 0;
// Input
for (int i = 0; i < 5; i++) {
[Link]("Student " + (i+1));
for (int j = 0; j < 3; j++) {
marks[i][j] = [Link]();
total += marks[i][j];
}
}
// Student averages
for (int i = 0; i < 5; i++) {
int sum = 0;
for (int j = 0; j < 3; j++) {
sum += marks[i][j];
}
[Link]("Average for student " + (i+1) + ": " + (sum/3.0));
}
// Overall average
[Link]("Class average: " + (total / 15));
}
}
b) Explain the difference between widening and narrowing type conversion.
Write a Java method that demonstrates both in a single logical flow. (4 marks)
Answer:
Widening: Automatic conversion (int → double)
Narrowing: Manual conversion (double → int)
public class CastingExample {
public static void main(String[] args) {
int num = 10;
double wide = num; // widening
double d = 9.78;
int narrow = (int) d; // narrowing
[Link](wide);
[Link](narrow);
}
}
c) Discuss the role and significance of the String[] args parameter in the Java
main() method. When and how is it used effectively? (4 marks)
Answer:
String[] args stores command-line arguments passed to the program.
It allows users to provide input during program execution.
Example:
public class Main {
public static void main(String[] args) {
[Link]("First argument: " + args[0]);
}
}
Used when running:
java Main Hello
✅ QUESTION THREE (15 MARKS)
a) Define a Java thread and outline the full lifecycle states of a thread with an
example use case in software development. (4 marks)
Answer:
A thread is a lightweight process used for concurrent execution.
Lifecycle states:
1. New
2. Runnable
3. Running
4. Blocked/Waiting
5. Terminated
Use case:
A web server handling multiple user requests simultaneously.
b) Design a multithreaded program with two threads:
i. One prints “Even: 2 4 6 8 10”
ii. The other prints “Odd: 1 3 5 7 9”
Ensure threads run concurrently and use [Link]() to control pacing. (6
marks)
Answer:
class EvenThread extends Thread {
public void run() {
for (int i = 2; i <= 10; i += 2) {
[Link]("Even: " + i);
try { [Link](500); } catch (Exception e) {}
}
}
}
class OddThread extends Thread {
public void run() {
for (int i = 1; i < 10; i += 2) {
[Link]("Odd: " + i);
try { [Link](500); } catch (Exception e) {}
}
}
}
public class TestThreads {
public static void main(String[] args) {
new EvenThread().start();
new OddThread().start();
}
}
c) Describe two common problems that arise in multithreaded applications
and how Java helps solve them using synchronization and inter-thread
communication. (5 marks)
Answer:
1. Race Condition: Multiple threads access shared data → inconsistent results
✔ Solved using synchronized keyword
2. Deadlock: Threads wait on each other indefinitely
✔ Solved using proper locking and wait() / notify()
✅ QUESTION FOUR (15 MARKS)
a) Develop a java program to create a simple Swing GUI application titled
“Fee Calculator”. It should:
i. Allow the user to input: Course Units, Cost per Unit
ii. Include a button: Calculate Total
iii. Display the total fee payable when the button is clicked (6 marks)
Answer:
import [Link].*;
import [Link].*;
public class FeeCalculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Fee Calculator");
JTextField units = new JTextField();
JTextField cost = new JTextField();
JTextField total = new JTextField();
JButton btn = new JButton("Calculate Total");
[Link](50, 50, 100, 30);
[Link](50, 100, 100, 30);
[Link](50, 150, 100, 30);
[Link](50, 200, 150, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
int u = [Link]([Link]());
int c = [Link]([Link]());
[Link]([Link](u * c));
}
});
[Link](units); [Link](cost); [Link](total); [Link](btn);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
b) Explain how event handling works in Java. What is the purpose of the
ActionListener interface and how is it implemented in a GUI application? (4
marks)
Answer:
Event handling responds to user actions (clicks, typing).
ActionListener listens for button clicks.
It is implemented using actionPerformed() method.
c) With the aid of a code snippet, explain the difference between using
BorderLayout and GridLayout in Java. Indicate one scenario where each
would be ideal. (5 marks)
Answer:
BorderLayout:
[Link](new BorderLayout());
[Link](button, [Link]);
👉 Divides layout into 5 regions
👉 Best for main window layouts
GridLayout:
[Link](new GridLayout(2,2));