Object Oriented Programming Exam - CP 215

THE UNIVERSITY OF DODOMA COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION Department of Computer Science and Engineering

End of Semester One University Examination for the 2024/2025 Academic Year

  • Course Name: Object Oriented Programming in Java
  • Paper Code Number: CP 215
  • Date of Examination: 27th February, 2025
  • Time: 11:45 – 14:45
  • Duration: 3 Hours
  • Venue(s): AUDITORIUM, EDU-LR1, CHAS_Library_1
  • Sitting Programme(s): BSc.SE2, HIS2, IS2, IDIT2, MTA2, CS2, CNISE2, CSDFE2, TE2, DCBE2, CE2, BIS2&BED ICT2.

SECTION A: (40 MARKS)

Answer ALL questions in this section.

Question One (1 Mark Each)

Read each question carefully and choose the most correct response.

i. Defining a class so that the implementation of the data and methods of the class are not known to the programmers who use the class is called:

  • A. Data Binding
  • B. Polymorphism
  • C. Encapsulation
  • D. Inheritance
  • E. Composition

ii. If a local variable of a method shop() belonging to a class called Walmart has the same name as a data member of Walmart, which value is used when shop() is executing?

  • A. the local variable’s
  • B. the class variable’s
  • C. the data member’s
  • D. this would cause a compiler error
  • E. both local variable’s and data member’s

iii. What will be printed?

public class Quest {
    public Quest() { }
    public void display( String goal, String days, int adj ) {
        System.out.println( "I am on a "+adj+" quest for the " +goal+" in "+days+" days." );
    }
    public static void main( String[] args ) {
        String adj = "perilous", goal = "sticky wicket";
        int days = 3;
        Quest q = new Quest();
        q.display( adj, goal, days );
    }
}
  • A. I am on a perilous quest for the 3 days.
  • B. I am on a sticky wicket quest for the perilous in 3 days.
  • C. I am on a perilous quest for the sticky wicket in 3 days.
  • D. I am on a 3 quest for the perilous in sticky wicket days.
  • E. I am on a perilous quest for the 3 in sticky wicket days.

iv. Complete the following Java statement to allow the instance of the Scanner class to read keyboard input. Scanner keyboard = new Scanner(______);

  • A. System.out
  • B. System.in
  • C. System.keyboard
  • D. System.input
  • E. System

v. Which subclass of Throwable is an exception checked at compile time?

  • A. NullPointerException
  • B. RuntimeException
  • C. IOException
  • D. ArrayIndexOutOfBoundsException
  • E. ArithmeticException

vi. Which of the following is NOT part of a method signature?

  • A. The method name
  • B. The return type
  • C. The number of parameters
  • D. The parameter types
  • E. Method body

vii. What will be printed when the program is executed?

public class Test {
    private static final int value = 5;
    public static void main( String[] args ) {
        int total, value = 4;
        total = value + value; // 4+4=8
        total = total + someMethod( total ); // 8 + 5 = 13
        System.out.println( total );
    }
    public static int someMethod( int val ) {
        return value; // Refers to the static final variable 'value' which is 5
    }
}
  • A. 13
  • B. 0
  • C. 16
  • D. 15
  • E. No output.

viii. What will be printed when the following program is executed?

class CP215 {
    public static void main(String[] args) {
        String str = "149";
        System.out.println(str + str + 3); // String concatenation: "149" + "149" + "3"
        int num = Integer.parseInt(str); // Convert string to int 149
        System.out.println(num + 3); // Integer addition: 149 + 3
    }
}
  • A. 301 and 152
  • B. 149+149+3 and 152
  • C. 1491493 and 152
  • D. 1491493 and 1493
  • E. 1491493 and 149+3

ix. Given the following piece of code. What will be printed?

1. class subException extends Exception{ }
2. class subSubException extends subException{ }
3. public class cc { void doStuff() throws SubException() { } // Typo & syntax error
4. class cc2 extends cc { void doStuff() throws SubSubException { } }
5. class cc3 extends cc { void doStuff() throws Exception { }} // Broader exception
6. class cc4 extends cc { void doStaff(int x)throws Exception { }} // Different method
7. class cc5 extends cc { void doStuff ()} // Missing exception, body
  • A. Compilation succeeds and nothing is printed
  • B. Compilation fails due to an error on line 3
  • C. Compilation fails due to an error on line 5
  • D. Compilation fails due to an error on line 6
  • E. Compilation fails due to an error on line 7

x. Given the following class and usage thereof, which of the labeled lines are incorrect?

public class Exam1 {
    private final int aQuandry;
    public Exam1( int quandry ) {
        I: aQuandry = quandry; // Valid: final variable can be initialized in constructor
    }
}
// ... In some other class, in some method:
II: Exam1 exam = new Exam1(); // Error: No default constructor
III: exam.aQuandry = 42; // Error: private and final field
IV: Exam1 = new Exam1( 99 ); // Error: Missing variable name
  • A. I, II
  • B. III, IV
  • C. II, III, IV
  • D. II, III
  • E. I, II, III, IV

Question Two (1 Mark Each)

Write True for the correct statement and False for the incorrect statement.

a. When an integer array is constructed with the new operator, the array’s cells are initialized to zero regardless of whether the array is a field.

b. If no exception arises in the try block, code in the finally clause is executed, and the next statement after try statement is executed.

c. An interface can contain fields. Each field in an interface is implicitly public, static and final.

d. Consider the statement M extends Y. this implies that M is class and Y is an interface or D is an interface like Y.

e. If one of the statements causes an exception that is not caught in any catch block, the other statements in try block are skipped, finally clause is executed, and then exception is passed to the caller of this method.

f. The keyword throw is used in method signature to declared exception explicitly.

g. A programmer defined class has no superclass unless the class is defined explicitly to extend a superclass.

h. A class that implements an interface must implement each method defined in the interface. If not, the class must be declared abstract.

i. Abstract classes are typically used to construct object of a particular class type whereas interface are typically used to define operations appropriate to a class type.

j. The executeUpdate() method is used to perform DML statements in JDBC.


Question Three

a. What happen when several catch blocks match the type of the thrown object? (2 Marks)

b. Read the following 2-dimension array declaration, and use it to answer the questions that follow. Note your code segment should include the part of the code that perform the specified task. Also in all cases, do not hardcode the length of your array. int [][] myArray = {{6,7,10,1,5},{67,9,7,50}, {10,20,30,40},{3,5,3} {2,1}};

i. Write a code segment that print the average of the array values. (2 Marks)

ii. Write a code segment to find out the row with the maximum sum. (4 Marks)

iii. Write a code segment to determine if all elements are positive. (2 Marks)


Question Four

a. For each of the following piece of code briefly explain what does it do. (1 Mark Each)

i. Assume the following method call is in an overridden earning method in a subclass: super.earnings( )

ii. Assume the following line of code appears as the first statement in a constructor’s body: super(firstArgument, secondArgument);

b. Consider the following classes and the main program to test these classes, where print is used to abbreviate System.out.println;

The main method of a tester class for the above classes

i. Will line 1 and 2 compile successfully? Briefly explain. (2 Mark)

ii. If line 3 compiles successfully, write down and explain the output. (2 Marks)

iii. State if Line 6 compiles. If yes, write down and explain the output. (2 Marks)

iv. State if Line 8 compiles. If yes, write down and explain the output. If no, suggest a fix using type casting. (2 Marks)


SECTION B: (60 MARKS)

Attempt any THREE (3) out of FOUR (4) questions provided.

Question Five (20 Marks)

a. What will be printed when the following code is executed? (3 Marks)

class B{
    public void p(double i){
        System.out.println(i*2);
    }
}
class A extends B{
    public void p(double i){
        System.out.println(i);
    }
}
public class Test{
    public static void main(String []args){
        A a = new A();
        a.p(5);   // 5.0 (int promoted to double, A's method called)
        a.p(5.0); // 5.0 (A's method called)
    }
}

b. The following code segment contain an error, carefully observe the code and write the correct line(s) of code into your answer booklet and write the output when the m(3). (3 Marks)

public class B{
    public static double m(int x) {
        int y = x;
        try{
            System.out.println(1);
            y = 5/x;                    // Line A: x=3, no exception
            System.out.println(2);       // Missing semicolon - ERROR
            return 5/(x+2);
        } catch (NullPointerException e) {
            System.out.println(3);
            y = 5/(x+1);
            System.out.println(4);
        }
        System.out.println(5);
        y= 4/x;
        System.out.println(6);
        return 1/x;
    }
}

c. What will be printed when the following code is executed? (3 Marks)

public class Demo {
    public static void main(String[] args) {
        m(new GraduateStudent()); // Output: "Student"
        m(new Student());         // Output: "Student"
        m(new Person());          // Output: "Person"
        m(new Object());          // Output: java.lang.Object@<hashcode>
    }
    public static void m(Object x) {
        System.out.println(x.toString());
    }
}
class GraduateStudent extends Student { }
class Student extends Person {
    public String toString() {
        return "Student";
    }
}
class Person {
    public String toString() {
        return "Person";
    }
}

d. Define a structure that can represent Animals. Animals have two behaviors; they can speak() and they can move(). By default, when an animal moves, the text ”This animal moves forward” is displayed. By default, when an animal speaks, the text ”This animal speaks” is displayed. A general Animal should not be able to be instantiated. Define also two classes, Goose and Lynx, that are Animals. Both Goose and Lynx behave such that where ”animal” is displayed in speak() or move(), ”goose” or ”lynx” is displayed by the appropriate classes. Finally, any instance of Goose can fly(), just as any Flying object can. An Airplane is also a Flying object. Define the Airplane class such that it is Flying and make sure that any instance of Goose is also Flying. The specific behaviors when instances of either class fly() are of your choice. Instances of either Goose or Airplane should be able to be stored in a variable of type Flying. (11 Marks)


Question Six (20 Marks)

Create an inheritance hierarchy that a university might use to represent its members. Design a class named Person, which encapsulates private instances such as name, address, phone number, and email address. From this class, derive two specific subclasses: Student and Employee. The Student class should include a constant representing the student’s class status, which can be one of four values: certificate, diploma, undergraduate, or postgraduate. The Employee class, on the other hand, should contain attributes for office location, salary, and a reference hire date of type Date. The Date class consisting of private members day, month, and year components. Further, extend the Employee class to create two additional subclasses: Faculty and Staff. The Faculty subclass should include attributes for office hours and academic rank, while the Staff subclass should have a title attribute. Ensure that each class overrides the toString method to display its class name along with the person’s name. Finally, develop a test program that instantiates objects for Person, Student, Employee, Faculty, and Staff, and subsequently invokes their respective toString() methods to demonstrate the functionality of your design. All values should be supplied from keyboard.

(20 Marks)


Question Seven (20 Marks)

You are required to implement a Java program for an advanced online recruitment system. First, define an interface named JobPortal with methods for posting jobs (postJob), retrieving job listings (getJobListings), applying for jobs (applyForJob), filtering jobs (filterJobs), and matching applicants to jobs (matchApplicants). Then, the JobPosting and Applicant classes are created with relevant attributes and constructors. Two classes, LinkedInPortal and UniversityJobBoard, implement the JobPortal interface, each with specific implementations for filterJobs() and matchApplicants() based on their respective platforms.

Finally, create a RecruitmentSystem class to store job postings, interact with different JobPortal implementations polymorphically, utilize all interface methods, and provide functionalities such as adding new job portals, sending notifications to applicants, and generating reports on job application statistics. The program must demonstrate effective use of polymorphism and implement all the required functionalities for job filtering, applicant matching, and system management. (20 Marks)*


Question Eight (20 Marks)

Figure 1 shows a schematic representation of Payable interface, Invoice, Employee and SalariedEmployee classes.

(Figure 1: Relationship between interface Payable, class Invoice, Employee and SalariedEmployee.)

Use the following information to write an application to determine payments for employees and invoices. You are required to create interface Payable, which contains method getPaymentAmount that returns a double amount that must be paid for an object of any class that implements the interface. Method getPaymentAmount is a general-purpose method to be implemented by classes that implements interface Payable. After declaring Payable interface, define class Invoice and Employee, such that they implement interface Payable. Classes Invoice and Employee both represent things for which the company must be able to calculate a payment amount. Both classes implement the interface Payable, so that a program can invoke method getPaymentAmount on Invoice objects and Employee objects. Class Invoice represents a simple invoice that contains billing information for only one kind of part. The class declares private instance variables partNumber, partDescription, quantity and pricePerItem. Class Invoice also contains a constructor, get methods and a toString method that returns a String representation of an Invoice object. The class Employee contains employee’s firstName, lastName, and employeeID. It also contains a constructor for initialization of instance variable and a toString method for returning its string representation. Salaried employee is paid a fixed weekly salary regardless of the number of hours worked. Therefore, SalariedEmployee class should contain a unique variable called salary, a constructor, a toString method for returning its string representation. Include main method to test your application. (20 Marks)


END OF EXAMINATION PAPER