0% found this document useful (0 votes)
29 views

Term1 Java Exam 2024_2025 Marking Guide

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Term1 Java Exam 2024_2025 Marking Guide

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

ACADEMIC YEAR: 2024--2025

LEVEL: YEAR2(A,B,C,D) TERM: ……I…….. Date: 16 December 2024

First term exam

OBJECT ORIENTED PROGRAMMING WITH JAVA

Timing: 180 minutes

Maximum:100 Marks

Instructions:
1. The test is written
2. Follow the guidelines provided and seek clarifications if need be.

3. The test is closed to any resource material.

4. Collaboration and any kind or cheating is prohibited and should be resulted into a GOOD
ZERO.

INSTRUCTORS

MUSANINYANGE MAHORO Larisse


HABANABASHAKA Jean Damascene

SECTION A: Each Question worth 2 Marks(50 Marks)


1. Which Java keyword(s) we use to create a constant value?
A)final
B)const
C)static
D) constant
E) static final
2. What “this ”does the keyword do when used in a constructor?
A. Calls the constructor of the superclass
B. Calls another constructor in the same class
C. Creates a new object of the current class
D. Refers to a method in the current class

3. What is the output of the following code?

class Test {
private int value = 42;

public int getValue() {


return value;
}
}

class Main {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.value);
}
}

a) 42
b)Compilation error
c) Runtime error
d) Undefined behavior

4. What is the return type of a constructor?


a) void
b) The class name
c) None
d) Object
5. What does the following code demonstrate?

try {
int number = Integer.parseInt("XYZ");
} catch (NumberFormatException e) {
System.out.println("Invalid format");
}

A. Type casting error


B. Handling checked exceptions
C. Handling unchecked exceptions
D. Compile-time polymorphism
6. What is the correct way to declare an abstract method?
a) abstract void method();
b) void method() abstract;
c) abstract method();
d) void abstract method();

7. Which of the following uses a lower-bounded wildcard?


A. <? extends Number>
B. <? super Integer>
C. <T extends Comparable<T>>
D. List<?>

8. Which principle ensures that a child class cannot directly access private members of a parent
class?
a) Encapsulation
b) Abstraction
c) Polymorphism
d) Inheritance
9. What will be the output of the following block of code?

class Base {
void display() {
System.out.println("Base display");
}
}

class Derived extends Base {


void display() {
System.out.println("Derived display");
}
}

class Main {
public static void main(String[] args) {
Base obj = new Derived();
obj.display();
}
}
a) Base display
b) Derived display
c) Compilation error
d) Undefined behavior
10. What is the purpose of the Pattern class in Java Regex?
a) To store a compiled regex
b) To validate a regex string
c) To execute a regex match
d) To iterate over regex matches
11. What is the purpose of the ResultSet object in JDBC?
A) To execute SQL queries
B) To store the connection details
C) To store and manipulate the data returned by a query
D) To update the database
12. What does <T> represent in a generic class or method?
A. The type of a method parameter
B. A placeholder for a specific type
C. A superclass type
D. A static type
13. What is the output of the following java codes?
public class Test {
public static void main(String[] args) {
System.out.println(method());
}

public static int method() {


try {
return 1;
} finally {
return 2;
}
}
}
A. 1
B. 2
C. Compilation error
D. Runtime error
14. Which class is used to read primitive data types in Java?
A. ObjectInputStream
B. DataInputStream
C. FileInputStream
D. BufferedReader
15. What will the following code do?
import java.io. *;

public class Test {

public static void main (String [] args) throws IOException {


System.out.println(method());
FileWriter writer = new FileWriter("C:\\external\\test.txt");
writer.write("Hello, world!");
writer.close();

}
A. Writes "Hello, world!" to a file named "test.txt"
B. Appends "Hello, world!" to an existing file named "test.txt"
C. Deletes "test.txt" and writes "Hello, world!"
D. Throws a runtime exception
16. Which of these is a valid declaration of a generic class?
A. public class Box<?>
B. public class Box<T>
C. public class Box<Generic>
D. Both B and C
17. Which regex will match a valid IP address?
a) ^(\\d{1,3}\\.){3}\\d{1,3}$
b) \\d+\\.\\d+\\.\\d+\\.\\d+
c) \\d{1,3}\\.{3}\\d{1,3}
d) None of the above
18. Which of the following statements is true for the given code?

List<?> list = new ArrayList<String>();


list.add(null);
A. Compilation error because of type mismatch
B. Compilation error because list.add() is invalid
C. Runtime error
D. Code compiles and runs successfully
19. Given the regex (ab)+, what will it match?
a) "ab"
b) "ababab"
c) "a"
d) Both a and b
20. Which of the following is NOT true about polymorphism?
a) It enables one object to take multiple forms.
b) It allows method overloading and overriding.
c) It cannot be achieved through inheritance.
d) It improves code flexibility.
21. The program below will compile
class Box{
int weight;
int width;
int depth;
public Box( int wt, int wd, int d){
this.weight=wt;
this.width=wd;
this.depth=d;
}
}
class Program{
public static void main(String []args){
Box box1=new Box();
}
}
a) Yes
b) No

22. Explain your choice on question 21.


The code will not compile because the Box class has a constructor that requires three
parameters (int wt, int wd, int d), but in the main method, you are attempting to
create a Box object with no arguments:
Box box1 = new Box(); // No arguments passed, but the constructor
requires three arguments.
Since no default constructor (a constructor with no parameters) is defined in the Box
class, and the class only has a constructor that takes three arguments, this will result in
a compilation error.

23. Differentiate Object Equality x.equals(y) and Reference Equality x == y.


Object Equality (x.equals(y)): It checks if the contents or state of two objects are
the same, typically by overriding the equals() method in the object's class. It is used
to compare the actual data or logical equality of objects.
Reference Equality (x == y): It checks if two references point to the exact same
object in memory (i.e., whether both variables refer to the same object). It compares
memory addresses, not the content of the objects.
In summary, x.equals(y) compares object values (if equals() is overridden), while x ==
y compares whether two references point to the same object.

24. Use try, catch and finally blocks to improve the method averageMark to handle
exceptions that can occur when the method is called.

class Program {

public static void averageMark( int totalMarks, int numberOfStudents){

System.out.println(totalMarks/numberOfStudents);

System.out.println("After displaying the average");

public static void main(String[] args) {

averageMark(0,0);

averageMark(30,3);

class Program {

public static void averageMark(int totalMarks, int numberOfStudents) {


try {

// Attempt to calculate the average

System.out.println(totalMarks / numberOfStudents); // This may throw


ArithmeticException

} catch (ArithmeticException e) {

// Handle division by zero error

System.out.println("Error: Cannot divide by zero.");

} catch (Exception e) {

// Handle any other general exceptions

System.out.println("An error occurred: " + e.getMessage());

} finally {

// This block will always execute, whether or not an exception occurs

System.out.println("After displaying the average");

public static void main(String[] args) {

averageMark(0, 0); // This will trigger the division by zero exception

averageMark(30, 3); // This will successfully display the average

25. Choose the best answer?


a) Set does not allow duplicates
b) List doesn’t allow duplicates
c) Set allows duplicates
d) List allows duplicates
e) a and b are correct
f) b and c are correct
g) a and d are correct
h) a and c are correct
SECTION B: Choose 4 Questions Only. / 20 Marks
26. What are the two key roles of this and super keywords in Java? Provide an example for each
scenario./5 Marks
this Keyword:
● Role: It refers to the current instance of the class. It is often used to distinguish
between instance variables and parameters when they have the same name, or to
refer to the current object in a method or constructor./ 1 Mark
class Car {
int speed;

// Constructor to set the speed of the car


public Car(int speed) {
this.speed = speed; // 'this' refers to the current object's speed field
}

public void displaySpeed() {


System.out.println("Speed: " + this.speed); // Refers to the current object's
speed
}
}

public class Program {


public static void main(String[] args) {
Car car = new Car(100);
car.displaySpeed(); // Output: Speed: 100
}
} /1.5 Marks

super Keyword:
● Role: It refers to the superclass (parent class) of the current object. It is used to call
superclass methods, constructors, and to access superclass fields that are hidden by
subclass fields./ 1 Mark
● class Animal {

● public void sound() {

● System.out.println("Animal makes a sound");

● }

● }

● class Dog extends Animal {


● public void sound() {

● super.sound(); // Calls the superclass method

● System.out.println("Dog barks");

● }

● }

● public class Program {

● public static void main(String[] args) {

● Dog dog = new Dog();

● dog.sound();

● }

● } / 1.5 Marks

27. What does the term WORA stand for, and why is Java considered to follow the WORA
principle?
WORA stands for "Write Once, Run Anywhere". It is a principle that signifies the
portability of Java programs. Java follows the WORA principle because Java code,
once compiled, can run on any platform that has a compatible Java Virtual Machine
(JVM), regardless of the underlying operating system or hardware architecture. This
is possible due to Java's architecture, which involves compiling the source code into
bytecode that is independent of the platform. The bytecode can then be executed on
any device that has the JVM installed, making Java highly portable.
Why Java follows the WORA principle:
1. Platform Independence: Java programs are compiled into bytecode (.class files) by
the Java compiler. This bytecode is not platform-specific, meaning the same
bytecode can run on any machine that has a JVM, which abstracts away the
platform-specific details.
2. JVM (Java Virtual Machine): The JVM interprets or compiles the bytecode into
machine-specific code for the underlying system. The JVM is available for various
platforms (Windows, Linux, MacOS, etc.), which enables Java programs to run on
those platforms without modification.
3. Java Libraries: Java's extensive standard libraries provide a consistent API, further
enhancing its portability. These libraries are designed to work uniformly across
platforms, contributing to the WORA principle.
Example:
If you write a Java program on a Windows system, you can compile the program into
bytecode. That bytecode can then be executed on any other system (like a Linux or
MacOS system) with the appropriate JVM installed, without needing any changes to
the code.
28. What is the difference between Collection and Collections? /5 Marks
 Collection (interface): It is the root interface in the Java Collections Framework
that represents a group of objects. It defines basic methods like add(), remove(),
contains(), and size() for working with collections of objects. Common
implementations include List, Set, and Queue.
 Collections (class): It is a utility class that provides static methods for operating on
or manipulating collections, such as sorting (sort()), reversing (reverse()), and
finding the maximum/minimum (max(), min()). It is not a collection itself but a
helper class for working with collections.

29. How does Java achieve multiple inheritance; provide an example to demonstrate this. / 5
Marks
Java does not support multiple inheritance (inheriting from more than one class)
directly through classes. However, Java achieves multiple inheritance through
interfaces. A class can implement multiple interfaces, allowing it to inherit behaviors
from multiple sources. This is a way to provide the benefits of multiple inheritance
while avoiding issues like the diamond problem (ambiguity in method
resolution)./2.5 Marks
interface Animal {
void eat();
}

interface Vehicle {
void drive();
}

class Car implements Animal, Vehicle {


public void eat() {
System.out.println("Car does not eat.");
}

public void drive() {


System.out.println("Car is driving.");
}
}

public class Program {


public static void main(String[] args) {
Car car = new Car();
car.eat(); // Output: Car does not eat.
car.drive(); // Output: Car is driving.
}
} / 2.5 Marks
30. What is the difference between * and + in regex? / 5 Marks
In regular expressions (regex), the symbols * and + are both quantifiers, but they
have different meanings:
1. * (Asterisk): It matches zero or more occurrences of the preceding element. This
means the pattern can match if the element appears any number of times, including
not at all./ 2.5 Marks
2. + (Plus): It matches one or more occurrences of the preceding element. This
means the pattern requires at least one occurrence of the element to match./2.5
Marks

31. Using examples, explain how an interface can have methods with implementation./5 Marks
In Java, an interface can have methods with implementation starting from Java 8
using the default and static keywords. These methods are provided with a default
behavior that implementing classes can either use directly or override.
1. default methods: A default method in an interface has a body (implementation). It
allows classes that implement the interface to inherit this default behavior without
needing to implement it themselves.
2. static methods: A static method in an interface can have an implementation, and it
belongs to the interface itself, not to the instances of the implementing classes.

interface Animal {
// Default method with implementation
default void sound() {
System.out.println("Animal makes a sound");
}

// Static method with implementation


static void staticMethod() {
System.out.println("This is a static method in the interface.");
}
}

class Dog implements Animal {


// Can override default method or use the default behavior
public void sound() {
System.out.println("Dog barks");
}
}

public class Program {


public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Output: Dog barks

Animal.staticMethod(); // Output: This is a static method in the interface.


}
}
SECTION C: This section is mandatory. Attempt all Questions. /30 Marks

32. Create a student class with fields for student ID, first name, last name, and age. Apply the
principles of encapsulation to the class. Use either the Comparator or Comparable interface to
sort students based on first name, then last name, age and lastly the ID. Then, create three
Student objects and demonstrate the sorting functionality. / 15 Marks
Using Comparable Interface:
class Student implements Comparable{// 2 Marks
//3 Marks
private int studentId;
private String firstName;
private String lastName;
private int age;

// Constructor
public Student(int studentId, String firstName, String lastName, int age) {
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

// Getters and Setters (Encapsulation)


public int getStudentId() { return studentId; }
public void setStudentId(int studentId) { this.studentId = studentId; }

public String getFirstName() { return firstName; }


public void setFirstName(String firstName) { this.firstName = firstName; }

public String getLastName() { return lastName; }


public void setLastName(String lastName) { this.lastName = lastName; }

public int getAge() { return age; }


public void setAge(int age) { this.age = age; }

// Implementing compareTo() for sorting based on first name, last name, age, and ID
@Override
public int compareTo(Student other) {
Student other=(Student)oth;
int result = this.firstName.compareTo(other.firstName);
if (result == 0) {
result = this.lastName.compareTo(other.lastName);
}
if (result == 0) {
result = Integer.compare(this.age, other.age);
}
if (result == 0) {
result = Integer.compare(this.studentId, other.studentId);
}
return result;
}
//Alternative
@Override
public int compareTo(Object o) {
Student other=(Student)o;

{
if(this.firstName.compareTo(other.firstName)){
return this.firstName.compareTo(other.firstName);
if(this.lastName.compareTo(other.lastName)){
return this.lastName.compareTo(other.lastName);
if(this.age.compareTo(other.age)){
return this.age.compareTo(other.age);
}

return this.studentId.compareTo(other.studentId);
}
@Override
public String toString() {
return studentId + ": " + firstName + " " + lastName + ", Age: " + age;
}
}

public class Program {


public static void main(String[] args) {
Student student1 = new Student(1, "John", "Doe", 20);
Student student2 = new Student(2, "Jane", "Smith", 22);
Student student3 = new Student(3, "John", "Smith", 18);

Student[] students = { student1, student2, student3 };


//Alternative
// ArrayList<Student> students=new ArrayList<Student>();
//or List<Student> students=new ArrayList<Student>();

// Sorting students based on the natural order defined in compareTo


Arrays.sort(students);
// Collections.sort(students);
//Alternatives with set
//or Set<Student> students=new TreeSet<Student>();
//or TreeSet<Student> students=new TreeSet<Student>();
//students.add(student1); students.add(student2); students.add(student3);
//or students.add(Arrays.asList(student1,student2,student3)’
// Displaying sorted students
for (Student student : students) {
System.out.println(student);
}
}
}

Using Comparator Interface:

import java.util.*;

class Student {
private int studentId;
private String firstName;
private String lastName;
private int age;

// Constructor
public Student(int studentId, String firstName, String lastName, int age) {
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

// Getters and Setters (Encapsulation)


public int getStudentId() { return studentId; }
public void setStudentId(int studentId) { this.studentId = studentId; }

public String getFirstName() { return firstName; }


public void setFirstName(String firstName) { this.firstName = firstName; }

public String getLastName() { return lastName; }


public void setLastName(String lastName) { this.lastName = lastName; }

public int getAge() { return age; }


public void setAge(int age) { this.age = age; }

@Override
public String toString() {
return studentId + ": " + firstName + " " + lastName + ", Age: " + age;
}
}

// Comparator class for custom sorting


class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
int result = s1.getFirstName().compareTo(s2.getFirstName());
if (result == 0) {
result = s1.getLastName().compareTo(s2.getLastName());
}
if (result == 0) {
result = Integer.compare(s1.getAge(), s2.getAge());
}
if (result == 0) {
result = Integer.compare(s1.getStudentId(), s2.getStudentId());
}
return result;
}
}

public class Program {


public static void main(String[] args) {
Student student1 = new Student(1, "John", "Doe", 20);
Student student2 = new Student(2, "Jane", "Smith", 22);
Student student3 = new Student(3, "John", "Smith", 18);

List<Student> students = new ArrayList<>(Arrays.asList(student1, student2, student3));

// Sorting students using the custom comparator


Collections.sort(students, new StudentComparator());

// Displaying sorted students


for (Student student : students) {
System.out.println(student);
}
}
}

33. Create a Java program with an interface Animal class that contains a method makeSound().
The makeSound() method should be implemented in two subclasses, Cat and Dog, each
returning their respective sounds. Additionally, include a generic class SoundPrinter that
accepts any animal, which has a method printSound that takes an animal object as a
parameter and prints the sound made by the animal. Finally, implement a Main class to create
instances of Cat and Dog, and use the SoundPrinter class to print the sounds of these animals /
15 Marks

// Animal interface with the makeSound method


interface Animal {
String makeSound();
}
// Cat class implements Animal interface
class Cat implements Animal {
@Override
public String makeSound() {
return "Meow";
}
}

// Dog class implements Animal interface


class Dog implements Animal {
@Override
public String makeSound() {
return "Bark";
}
}

// Generic SoundPrinter class


class SoundPrinter<T extends Animal> {
public void printSound(T animal) {
System.out.println(animal.makeSound());
}
}

// Main class to test the program


public class Main {
public static void main(String[] args) {
// Create instances of Cat and Dog
Animal cat = new Cat();
Animal dog = new Dog();

// Create an instance of SoundPrinter


SoundPrinter<Animal> soundPrinter = new SoundPrinter<Animal>();

// Print sounds of both animals


soundPrinter.printSound(cat); // Output: Meow
soundPrinter.printSound(dog); // Output: Bark
}
}

—--- Merry Christmas and Happy New Year 2025—---

You might also like