MKU Java Programming (DIT3104) – 2024/2025
Full Questions & Answers
SECTION A – QUESTION ONE (Compulsory)
Q1a) Discuss three benefits of Object Oriented Programming. (6 Marks)
1. Reusability – Code written in classes can be reused in other programs through inheritance,
saving time and effort
2. Modularity – A program is divided into objects/classes making it easier to manage, debug and
update
3. Data Security – Encapsulation hides sensitive data from outside access, protecting it using
access modifiers like private
Q1b) Discuss three parts of a class diagram and illustrate using an example. (6 Marks)
A class diagram has three parts:
1. Class Name – The name of the class at the top
2. Attributes/Member Variables – The properties of the class in the middle
3. Methods/Operations – The functions the class can perform at the bottom
Example:
+----------------------+
| Student | ← Class Name
+----------------------+
| - name: String | ← Attributes
| - age: int |
| - regNo: String |
+----------------------+
| + getName(): String | ← Methods
| + setAge(int): void |
+----------------------+
Q1c) Differentiate between the following: (6 Marks)
i) Private access modifier vs Public access modifier
Private Public
Accessible only within the same class Accessible from any other class
Used to hide/protect data Used to expose methods and data
Example: private int age; Example: public void display()
ii) Set method vs Get method
Set Method Get Method
Used to assign/change a value to a variable Used to retrieve/read a variable's value
Example: void setName(String n){ name=n; } Example: String getName(){ return name; }
iii) Member variables vs Member methods
Member Variables Member Methods
Variables declared inside a class that store data Functions declared inside a class that perform actions
Example: int age; Example: void display(){}
Q1d) Write a Java program that accepts length and width of a rectangle and computes and displays
the area. (6 Marks)
java
import [Link];
public class Rectangle {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter length: ");
double length = [Link]();
[Link]("Enter width: ");
double width = [Link]();
double area = length * width;
[Link]("Area of rectangle = " + area);
}
}
Q1e) Discuss three types of programming errors. (6 Marks)
1. Syntax Error – Mistakes in the grammar/rules of the language. The program won't compile.
Example: missing semicolon int x = 5
2. Runtime Error – Errors that occur while the program is running. Example: dividing by zero
causes the program to crash
3. Logic Error – The program runs without crashing but produces wrong results. Example: writing
area = length + width instead of length * width
SECTION B – Answer ANY TWO Questions
QUESTION TWO
Q2a) Describe the basic phases of developing Java programs. (8 Marks)
1. Problem Definition – Understand and clearly state what the program should do
2. Program Design – Plan the solution using flowcharts or pseudocode
3. Coding – Write the actual Java source code using a text editor or IDE
4. Compilation – The Java compiler converts source code (.java) into bytecode (.class). Syntax
errors are caught here
5. Testing and Debugging – Run the program and fix any runtime or logic errors
6. Documentation – Add comments and write manuals explaining how the program works
7. Deployment – Release the finished program for users
8. Maintenance – Update and fix the program over time as needed
Q2b) Write a Java program that accepts student marks for Maths, Kiswahili, English and French,
computes total, average and displays grade. (8 Marks)
java
import [Link];
public class StudentGrade {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Maths mark: ");
double maths = [Link]();
[Link]("Enter Kiswahili mark: ");
double kisw = [Link]();
[Link]("Enter English mark: ");
double eng = [Link]();
[Link]("Enter French mark: ");
double french = [Link]();
double total = maths + kisw + eng + french;
double average = total / 4;
String grade;
if (average >= 80) {
grade = "Distinction";
} else if (average >= 60) {
grade = "Credit";
} else if (average >= 50) {
grade = "Credit II";
} else if (average >= 40) {
grade = "Pass";
} else {
grade = "Fail";
}
[Link]("Total: " + total);
[Link]("Average: " + average);
[Link]("Grade: " + grade);
}
}
Q2c) Differentiate between pseudocode and a flowchart. (4 Marks)
Pseudocode Flowchart
Written in plain English-like statements Uses diagrams/symbols to show steps
Text-based representation Visual/graphical representation
Easier to write and convert to code Easier to understand at a glance
Pseudocode Flowchart
Example: IF age > 18 THEN print "Adult" Uses arrows, diamonds, rectangles
QUESTION THREE
Q3a) Write a program that asks user's name, converts to uppercase and greets them. (6 Marks)
java
import [Link];
public class Greet {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
String upperName = [Link]();
[Link]("Hello, " + upperName + ", nice to meet you!");
}
}
Output if name is Peter:
Hello, PETER, nice to meet you!
Q3b) Write a Java program using a loop to generate 7 numbers in series 2,6,18... and compute their
sum. (8 Marks)
The series is: each number × 3 gives the next (2, 6, 18, 54, 162, 486, 1458)
java
public class Series {
public static void main(String[] args) {
int number = 2;
int sum = 0;
[Link]("The series:");
for (int i = 1; i <= 7; i++) {
[Link](number);
sum += number;
number = number * 3;
}
[Link]("Sum = " + sum);
}
}
Output:
2
6
18
54
162
486
1458
Sum = 2186
Q3c) Discuss three types of Java comments. (6 Marks)
1. Single-line comment – Used to comment one line only
java
// This is a single line comment
2. Multi-line comment – Used to comment multiple lines
java
/* This is a
multi-line comment */
3. Documentation comment (Javadoc) – Used to generate HTML documentation for a program
java
/** This method calculates area
* @param length the length
* @return area value
*/
QUESTION FOUR
Q4a) Discuss any three types of Java operators. (6 Marks)
1. Arithmetic Operators – Used for mathematical calculations
o +, -, *, /, %
o Example: int sum = 5 + 3; gives 8
2. Comparison/Relational Operators – Used to compare two values, returns true or false
o ==, !=, >, <, >=, <=
o Example: 5 > 3 returns true
3. Logical Operators – Used to combine multiple conditions
o && (AND), || (OR), ! (NOT)
o Example: if (age > 18 && employed == true)
Q4b) Write a Java program that checks if a number entered by user is Even or Odd. (7 Marks)
java
import [Link];
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
if (number % 2 == 0) {
[Link](number + " is Even");
} else {
[Link](number + " is Odd");
}
}
}
Q4c) Implement a Java program that uses an array to store days of the week and prints them. (7
Marks)
public class DaysOfWeek {
public static void main(String[] args) {
String[] days = {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
[Link]("Days of the week:");
for (int i = 0; i < [Link]; i++) {
[Link](days[i]);
}
}
}
QUESTION FIVE
Q5a) Show the exact output of the following main() routine. (4 Marks)
java
int x, y;
x = 5;
y = 1;
while (x > 0) {
x = x - 1;
y = y * x;
[Link](y);
}
Tracing through:
Iteration x before x after (x-1) y = y * x
1 5 4 1×4 = 4
2 4 3 4×3 = 12
3 3 2 12×2 = 24
4 2 1 24×1 = 24
5 1 0 24×0 = 0
Exact Output:
4
12
24
24
0
Q5b) State four rules for naming member variables. (4 Marks)
1. Must start with a letter, underscore _ or dollar sign $ — not a number
2. Cannot use Java reserved keywords e.g. int, class, static
3. No spaces allowed — use camelCase e.g. studentName
4. Names are case-sensitive — age and Age are different variables
Q5c) What is the main difference between a while loop and a do-while loop? (4 Marks)
While Loop Do-While Loop
Checks condition AFTER
Checks condition BEFORE executing
executing
May never execute if condition is false Always executes at least ONCE
Example: while(x>0){...} Example: do{...}while(x>0);
Q5d) Define garbage collection and explain how it is used. (4 Marks)
Garbage collection is the automatic process in Java where the JVM (Java Virtual Machine) identifies and
removes objects from memory that are no longer being used by the program.
How it works:
When an object has no more references pointing to it, the garbage collector marks it for
deletion
The JVM automatically frees up that memory without the programmer doing it manually
This prevents memory leaks and improves program performance
The programmer can suggest garbage collection using [Link]() but cannot force it
Q5e) Differentiate between break and continue statements. (4 Marks)
Break Continue
Skips the current iteration only and continues
Completely exits/stops the loop
the loop
Program goes back to check the loop
Program moves to code after the loop
condition
Example: exits loop when number found Example: skip printing even numbers
java
// Break example
for(int i=1; i<=5; i++){
if(i==3) break; // stops at 3
[Link](i); // prints 1, 2
}
// Continue example
for(int i=1; i<=5; i++){
if(i==3) continue; // skips 3
[Link](i); // prints 1,2,4,5
}
SECTION A – QUESTION ONE (Compulsory)
Q1a) Identify the principle enforced by declaring a class's attributes as private. (5 Marks)
The principle is Encapsulation.
Encapsulation means hiding the internal data of a class from outside access. By declaring attributes as
private, they cannot be accessed directly from outside the class. Instead, they are accessed through
public getter and setter methods, protecting the data from unauthorized changes.
Q1b) Predict the output of: [Link](10 + "5"); (5 Marks)
Output:
105
Reason: In Java, when you add an integer and a String, Java converts the integer to a String and
performs concatenation, not addition. So 10 becomes "10" and joins with "5" to give "105".
Q1c) Name a loop where the condition is checked after the loop body executes. (5 Marks)
Do-While loop
java
do {
// loop body executes first
} while (condition); // condition checked after
It always executes at least once regardless of the condition.
Q1d) Write the statement to define a class-level constant integer named MAX_SIZE with value 500. (5
Marks)
java
static final int MAX_SIZE = 500;
static – belongs to the class, not an instance
final – makes it a constant (value cannot be changed)
Q1e) Explain two data types used for storing whole numbers. (5 Marks)
1. int – Stores whole numbers from about -2 billion to +2 billion (32-bit). Most commonly used.
o Example: int age = 25;
2. long – Stores very large whole numbers (64-bit). Used when int is too small.
o Example: long population = 8000000000L;
Q1f) State one key advantage of Java's approach to portability. (5 Marks)
Java follows the "Write Once, Run Anywhere" (WORA) principle.
Java code is compiled into bytecode which runs on the Java Virtual Machine (JVM). Since JVM is
available on all major operating systems (Windows, Mac, Linux), the same compiled program runs on
any platform without rewriting or recompiling.
SECTION B – Answer ANY TWO Questions
QUESTION TWO
Q2a) Develop a switch statement that prints "Weekday" for values 1–5 and "Weekend" for values 6–7
of an int day variable. (6 Marks)
java
int day = 3; // change this value to test
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
[Link]("Weekday");
break;
case 6:
case 7:
[Link]("Weekend");
break;
default:
[Link]("Invalid day");
}
Q2b) Using a valid example, differentiate between a class and an object. (6 Marks)
Class Object
A blueprint or template An instance created from the class
Defined once Can be created many times
Does not occupy memory until instantiated Occupies memory when created
Example:
java
// Class (blueprint)
class Car {
String brand;
int year;
}
// Objects (instances of the class)
Car car1 = new Car(); // object 1
[Link] = "Toyota";
Car car2 = new Car(); // object 2
[Link] = "Honda";
Car is the class. car1 and car2 are objects.
Q2c) Correct this code and state the naming rule it broke. (4 Marks)
java
int 2ndPlace;
Problem: Variable names cannot start with a number.
Corrected code:
java
int secondPlace;
Naming rule broken: A variable name must begin with a letter, underscore _, or dollar sign $. It cannot
start with a digit.
Q2d) Determine the value of: boolean result = (15 > 10) && (4 == 5); (4 Marks)
(15 > 10) → true
(4 == 5) → false
true && false → false
Result = false
&& (AND) only returns true if both conditions are true. Since one is false, the result is false.
QUESTION THREE
Q3a) Construct a method header for a public method named greet that returns a String and requires a
String parameter called name. (6 Marks)
java
public String greet(String name)
public – accessible from anywhere
String – return type
greet – method name
String name – parameter
Full method example:
java
public String greet(String name) {
return "Hello, " + name + "!";
}
Q3b) Justify the use of double data type over float for scientific calculations. (6 Marks)
1. Precision – double is 64-bit and gives about 15–16 decimal digits of precision. float is 32-bit and
gives only 6–7 digits. Scientific calculations need high precision.
2. Range – double handles a much larger range of values than float
3. Default in Java – Java treats decimal numbers as double by default, so using double avoids
casting errors
4. Accuracy – Rounding errors are smaller with double, which is critical in scientific and financial
calculations
Q3c) Evaluate the expression: int x = 10; x += 5 * 2; What is the final value of x? (4 Marks)
5 * 2 = 10 (multiplication done first)
x += 10 means x = x + 10 = 10 + 10 = 20
Final value of x = 20
Q3d) Convert this for loop to a while loop: (4 Marks)
java
for(int i=0; i<3; i++){
[Link]("Hello");
}
While loop equivalent:
java
int i = 0;
while (i < 3) {
[Link]("Hello");
i++;
}
QUESTION FOUR
Q4a) Explain the role of the static keyword in the main method's declaration. (6 Marks)
public static void main(String[] args)
The static keyword means the main method belongs to the class itself, not to any object. This allows the
JVM to call main() directly without creating an object of the class first. Without static, the JVM would
need to create an instance of the class before running the program, which is not possible at startup.
Q4b) Identify the special method called when an object is created with the new keyword. (6 Marks)
The method is called a Constructor.
It has the same name as the class
It has no return type
It is automatically called when an object is created using new
java
class Student {
String name;
// Constructor
Student(String n) {
name = n;
}
}
// Constructor called here
Student s = new Student("John");
Q4c) Write an if statement to check if a number is both positive and even. (4 Marks)
java
int number = 8;
if (number > 0 && number % 2 == 0) {
[Link](number + " is positive and even");
}
Q4d) Define method overloading. (4 Marks)
Method overloading is when a class has two or more methods with the same name but different
parameters (different number or type of parameters).
java
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) { // overloaded
return a + b;
}
}
Java decides which method to call based on the arguments passed.
Q4e) State one key advantage of Java's "Write Once, Run Anywhere" principle. (4 Marks)
A Java program compiled on one operating system (e.g. Windows) runs on any other OS (e.g. Linux or
Mac) without modification, as long as a JVM is installed. This saves time and reduces development cost
since separate versions for each platform are not needed.
QUESTION FIVE
Q5b) Write the statement to declare and initialize a char variable with the letter 'A'. (4 Marks)
java
char letter = 'A';
Note: char values use single quotes, not double quotes.
Q5c) Name the principle that allows a Car class to inherit properties from a Vehicle class. (4 Marks)
The principle is Inheritance.
java
class Vehicle {
String brand;
}
class Car extends Vehicle { // Car inherits from Vehicle
int doors;
}
extends is the keyword used. Car inherits all attributes and methods of Vehicle.
Q5d) Write code to print "Pass" if a student scores 50 or more, and "Fail" otherwise. (4 Marks)
java
int score = 65;
if (score >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}
Q5e) Write Java code that takes in two integers and displays their sum. (4 Marks)
java
import [Link];
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();
int sum = num1 + num2;
[Link]("Sum = " + sum);
}
}