OOP - Object Oriented Programming, Past Papers

Object Oriented Programming (OOP) Past Paper 2018 – MSc IT 2nd Term UOS

OOP Past Paper 2018 MSc IT 2nd Term UOS

University of Sargodha (UOS) M.Sc. IT 2nd term Object Oriented Programming (CMP-2123) past paper 2018, with the full question paper in text form and solved answers. The paper is Java-based, and all programs below are compiled and tested.

Print / download (A4, high quality): Full-size paper

OOP Past Paper 2018 MSc IT (text version)

University of Sargodha – M.Sc. 2nd Term Examination 2018, Subject: Information Technology
Paper: Object Oriented Programming (CMP-2123) · Time: 2:30 hours · Maximum marks: 60
Note: Objective part is compulsory. Attempt any four questions from the subjective part.

Objective part (compulsory) – Q1: Write short answers in 2–3 lines each (12 × 2)

  1. What is a static method? Give some examples from any Java class.
  2. What is the purpose of Information Hiding?
  3. Can a constructor call another constructor using the this keyword? Give an example.
  4. What is a void reference?
  5. Can a catch() block be written without a try() block?
  6. Can we instantiate an interface?
  7. When is the swing package used?
  8. What is the purpose of the instanceof operator?
  9. What is the this reference and its purpose? Give an example.
  10. Can we override final methods? If not, why?
  11. What is the purpose of a Wrapper class?
  12. Differentiate between throw and throws.

Subjective part (4 × 9)

Q2. Create a class employee (id, name). Inherit two classes named collegeEmployee (salary) and Faculty (contract_duration) from it. Write appropriate constructors, print() and get() functions for each class. Write an application that demonstrates using objects of each class.

Q3. Write down a class Complex having data members (real, imaginary) that implements Serializable. The program should also contain the constructor and a method to read a complex number from the user. The program should throw an exception if the imaginary part is negative. Also override the toString() method.

Q4. Create an abstract class Furniture (color, price). Include get and set methods for these fields; the setPrice() method is abstract. Create two subclasses Table (length, width) and Chair (color) from Furniture and include appropriate setPrice() methods in each class. Finally, write an application that uses the Furniture class and subclasses to display information about instances.

Q5. Create an interface Playable having the method play(). Create two classes CD (title, playtime) and DVD (title, playtime) that implement Playable. Give appropriate constructors. Also implement the method play() that prints the title and playtime. Demonstrate polymorphic behavior of method play using the interface Playable.

Q6. Write an application that calculates the grade of a student based on marks entered. The integer number should be entered from the keyboard (via a JTextField). An un-editable text field should be used to display the grade against the entered marks when the user clicks the Calculate Grade button. Use the following formula for the calculation.
Hint: if (marks >= 80) grade = ‘A’; if (marks >= 70 && marks < 80) grade = ‘B’; if (marks >= 60 && marks < 70) grade = ‘C’; if (marks >= 50 && marks < 60) grade = ‘C’; if (marks < 50) grade = ‘F’.

Q7. Write a program that concatenates the contents of file2 into the contents of file1, i.e. it should append the contents of a text file at the end of another file.

Original paper (scanned copy)

The clean paper above is retyped by Shining Study from this original University of Sargodha question paper. Click a scan to view it full size.

OOP Past Paper 2018 MSc IT 2nd Term UOS – original scan

Solved answers

Q1 – Short questions

(i) Static method: a method that belongs to the class, not to an object, so it is called with the class name and cannot use instance fields or this. Examples: Math.sqrt(), Math.max(), Integer.parseInt(), String.valueOf(), Arrays.sort(), and main() itself.

(ii) Information hiding: keeping an object’s internal data and implementation private and exposing only a public interface. It protects data from invalid changes, reduces coupling and lets the internals change without breaking other code.

(iii) Constructor chaining with this(): yes. this(...) calls another constructor of the same class and must be the first statement:

class Box {
    int l, w;
    Box() { this(1, 1); }            // calls Box(int, int)
    Box(int l, int w) { this.l = l; this.w = w; }
}

(iv) void reference: Java has no “void reference” type; void is only a return type meaning a method returns nothing. A reference variable that points to no object holds null; using it causes a NullPointerException. (In C/C++ a void pointer is a generic pointer; Java uses Object references for that.)

(v) catch without try: no. A catch block must follow a try block, otherwise it is a compile-time error. A try may be followed by catch, finally or both.

(vi) Instantiate an interface: no, new Runnable() alone is not allowed because an interface has no implementation. We can only create an object of a class that implements it (including an anonymous class or a lambda) and hold it in an interface reference: Runnable r = () -> System.out.println("run");

(vii) When swing is used: to build desktop GUI applications – windows, buttons, text fields, menus, tables (JFrame, JButton, JTextField…). Swing components are lightweight, platform-independent and have a pluggable look and feel.

(viii) instanceof: checks at run time whether an object is an instance of a class or interface and returns true/false: if (b instanceof Parrot) .... It is used before downcasting to avoid ClassCastException.

(ix) this reference: refers to the current object. It separates fields from parameters with the same name, passes the current object to another method, and calls another constructor. Example: Student(String name) { this.name = name; }

(x) Overriding final methods: no. A method declared final cannot be overridden by a subclass; the compiler gives an error. final is used so important behaviour (e.g. security checks) cannot be changed by subclasses.

(xi) Wrapper class purpose: to treat primitives as objects (Integer, Double, Character…) so they can be used in collections like ArrayList, can be null, and get useful methods such as Integer.parseInt() and Double.valueOf(). Autoboxing converts automatically.

(xii) throw vs throws: throw is used inside a method to throw one exception object; throws is written in the method signature to declare exceptions the method may pass to the caller. Example: void check(int a) throws IOException { if (a < 0) throw new IllegalArgumentException(); }

Q2 – employee, collegeEmployee and Faculty

class Employee {
    protected int id;
    protected String name;
    public Employee(int id, String name) { this.id = id; this.name = name; }
    public int getId() { return id; }
    public String getName() { return name; }
    public void print() { System.out.println("ID: " + id + ", Name: " + name); }
}

class CollegeEmployee extends Employee {
    private double salary;
    public CollegeEmployee(int id, String name, double salary) {
        super(id, name);
        this.salary = salary;
    }
    public double getSalary() { return salary; }
    @Override public void print() {
        super.print();
        System.out.println("  College employee, salary: " + salary);
    }
}

class Faculty extends Employee {
    private int contractDuration;   // in months
    public Faculty(int id, String name, int contractDuration) {
        super(id, name);
        this.contractDuration = contractDuration;
    }
    public int getContractDuration() { return contractDuration; }
    @Override public void print() {
        super.print();
        System.out.println("  Faculty, contract: " + contractDuration + " months");
    }
}

public class EmployeeApp {
    public static void main(String[] args) {
        Employee e = new Employee(1, "Ali");
        CollegeEmployee c = new CollegeEmployee(2, "Sana", 85000);
        Faculty f = new Faculty(3, "Dr. Imran", 24);
        e.print(); c.print(); f.print();
        System.out.println(c.getName() + " earns " + c.getSalary());
    }
}

Q3 – Serializable Complex class

import java.io.Serializable;
import java.util.Scanner;

class Complex implements Serializable {
    private static final long serialVersionUID = 1L;
    private double real, imaginary;

    public Complex(double real, double imaginary) {
        if (imaginary < 0)
            throw new IllegalArgumentException("Imaginary part cannot be negative");
        this.real = real;
        this.imaginary = imaginary;
    }

    public static Complex read(Scanner in) {
        System.out.print("Enter real and imaginary parts: ");
        double r = in.nextDouble(), i = in.nextDouble();
        return new Complex(r, i);          // throws if i is negative
    }

    @Override public String toString() { return real + " + " + imaginary + "i"; }
}

public class ComplexApp {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try {
            Complex c = Complex.read(in);
            System.out.println("Complex number: " + c);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Input 3 4 prints 3.0 + 4.0i; input 3 -4 prints the error message.

Q4 – Abstract Furniture with Table and Chair

abstract class Furniture {
    protected String color;
    protected double price;
    public Furniture(String color) { this.color = color; }
    public String getColor() { return color; }
    public void setColor(String color) { this.color = color; }
    public double getPrice() { return price; }
    public abstract void setPrice();          // each subclass decides its price
    public String toString() { return getClass().getSimpleName() + " [color=" + color + ", price=" + price + "]"; }
}

class Table extends Furniture {
    private double length, width;
    public Table(String color, double length, double width) {
        super(color); this.length = length; this.width = width; setPrice();
    }
    @Override public void setPrice() { price = 2000 + length * width * 50; }   // based on size
}

class Chair extends Furniture {
    public Chair(String color) { super(color); setPrice(); }
    @Override public void setPrice() { price = color.equalsIgnoreCase("black") ? 4500 : 3500; }
}

public class FurnitureApp {
    public static void main(String[] args) {
        Furniture[] items = { new Table("Brown", 6, 3), new Chair("Black"), new Chair("White") };
        for (Furniture f : items) System.out.println(f);
    }
}

Output: Table [color=Brown, price=2900.0], Chair [color=Black, price=4500.0], Chair [color=White, price=3500.0]. The pricing rules are our own example; any sensible rule is fine as long as setPrice() is abstract in Furniture.

Q5 – Playable interface with CD and DVD

interface Playable {
    void play();
}
class CD implements Playable {
    private String title; private int playtime;     // minutes
    public CD(String title, int playtime) { this.title = title; this.playtime = playtime; }
    public void play() { System.out.println("Playing CD: " + title + " (" + playtime + " min)"); }
}
class DVD implements Playable {
    private String title; private int playtime;
    public DVD(String title, int playtime) { this.title = title; this.playtime = playtime; }
    public void play() { System.out.println("Playing DVD: " + title + " (" + playtime + " min)"); }
}
public class PlayableDemo {
    public static void main(String[] args) {
        Playable[] list = { new CD("Coke Studio Hits", 58), new DVD("Documentary", 95) };
        for (Playable p : list) p.play();     // polymorphic call through the interface
    }
}

Q6 – Swing grade calculator

The printed hint gives ‘C’ for both 60–69 and 50–59; the second one is almost certainly a typo for ‘D’, so the program below uses D for 50–59. Change one line if your teacher wants ‘C’.

import javax.swing.*;
import java.awt.*;

public class GradeApp extends JFrame {
    private JTextField marksField = new JTextField(6);
    private JTextField gradeField = new JTextField(4);

    public GradeApp() {
        super("Grade Calculator");
        setLayout(new FlowLayout());
        gradeField.setEditable(false);                  // un-editable result field
        JButton calc = new JButton("Calculate Grade");
        add(new JLabel("Marks:")); add(marksField);
        add(calc);
        add(new JLabel("Grade:")); add(gradeField);
        calc.addActionListener(e -> {
            try {
                int m = Integer.parseInt(marksField.getText().trim());
                gradeField.setText(String.valueOf(grade(m)));
            } catch (NumberFormatException ex) {
                gradeField.setText("?");
            }
        });
        setSize(280, 120);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    static char grade(int marks) {
        if (marks >= 80) return 'A';
        if (marks >= 70) return 'B';
        if (marks >= 60) return 'C';
        if (marks >= 50) return 'D';
        return 'F';
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(GradeApp::new);
    }
}

Q7 – Append file2 to the end of file1

import java.io.*;

public class AppendFile {
    public static void main(String[] args) {
        try (BufferedReader in = new BufferedReader(new FileReader("file2.txt"));
             BufferedWriter out = new BufferedWriter(new FileWriter("file1.txt", true))) {  // true = append
            String line;
            while ((line = in.readLine()) != null) {
                out.write(line);
                out.newLine();
            }
            System.out.println("Contents of file2.txt appended to file1.txt");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

The key is new FileWriter("file1.txt", true): the second argument opens the file in append mode instead of overwriting it.

Answers prepared by Shining Study for revision. Check them against your class notes and teacher’s guidance.

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.