Blog
Object Oriented Programming Past Paper 2014 – MSc IT 2nd Term UOS (CMP-2123)
University of Sargodha Object Oriented Programming (CMP-2123) paper for M.Sc. IT 2nd term, 2014 exam (session 2013-15, 60 marks, 2:30 hours). The paper has been retyped, and solved answers are given below for all 12 short questions and all six long questions, with complete Java programs that were compiled and tested.
Solved answers
Q1 – Short answers (12 × 2)
i. Class: A blueprint that defines the fields (data) and methods (behaviour) of objects. Example: class Student { String name; void show() { … } } – each new Student() is an object of this class.
ii. Object-oriented programming: A programming style that models a program as interacting objects, built on encapsulation, inheritance, polymorphism and abstraction (Java, C++).
iii. Method overriding: Redefining in a subclass a method that has the same name, parameters and return type as in the superclass, so the subclass version runs at run time (dynamic binding). Marked with @Override.
iv. java.lang package: The core package imported automatically into every Java program. It contains Object, String, Math, System, wrapper classes (Integer, Double), Thread and the basic exceptions.
v. Purpose of packages: To group related classes and interfaces, avoid name conflicts, control access (package-private) and make code easier to find and reuse, e.g. java.util, java.io.
vi. Access specifiers in Java: public, protected, default (package-private, no keyword) and private.
vii. Interface vs abstract class: An abstract class can have fields, constructors and both abstract and concrete methods, and a class can extend only one. An interface has constants and abstract (plus default/static) methods only, and a class can implement many interfaces.
viii. final with a class: A final class cannot be extended (inherited). It is used for security and design reasons, e.g. java.lang.String is final.
ix. Simple use of ArrayList: A resizable array: ArrayList<String> list = new ArrayList<>(); list.add("Ali"); list.add("Sara"); System.out.println(list.get(0) + " " + list.size());
x. super keyword: Refers to the immediate superclass: super(…) calls the parent constructor, and super.method() or super.field accesses overridden methods or hidden fields of the parent.
xi. Encapsulation: Wrapping data and the methods that use it into one class and hiding the data (private fields) behind public getter and setter methods, so it can only be changed in controlled ways.
xii. Joining two strings: Use the + operator (s1 + s2), the concat() method (s1.concat(s2)), or StringBuilder.append() for many joins.
Q2 – Time class
Fields are private (encapsulation), with an overloaded constructor, getters and setters that validate the values, printTime() and an overridden toString(). Output: 14:00:00 and 09:45:30 (tested).
public class Time {
private int hour, minute, second;
public Time() { this(0, 0, 0); }
public Time(int hour, int minute, int second) {
setHour(hour); setMinute(minute); setSecond(second);
}
public int getHour() { return hour; }
public int getMinute() { return minute; }
public int getSecond() { return second; }
public void setHour(int h) { hour = (h >= 0 && h < 24) ? h : 0; }
public void setMinute(int m) { minute = (m >= 0 && m < 60) ? m : 0; }
public void setSecond(int s) { second = (s >= 0 && s < 60) ? s : 0; }
public void printTime() { System.out.println(this); }
@Override
public String toString() {
return String.format("%02d:%02d:%02d", hour, minute, second);
}
public static void main(String[] args) {
Time t1 = new Time();
Time t2 = new Time(9, 45, 30);
t1.setHour(14);
t1.printTime(); // 14:00:00
t2.printTime(); // 09:45:30
System.out.println("t2 = " + t2);
}
}Q3 – Point and Circle: up-casting
Up-casting is assigning a subclass object to a superclass reference (Point p = c;). It is automatic and safe. Through p only Point members are visible, but an overridden method still runs the Circle version. Output: “Circle at (2, 3) radius 5.0” and “Area = 78.54” (tested).
class Point {
protected int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
void show() { System.out.println("Point(" + x + ", " + y + ")"); }
}
class Circle extends Point {
private double radius;
Circle(int x, int y, double radius) { super(x, y); this.radius = radius; }
double area() { return Math.PI * radius * radius; }
@Override
void show() { System.out.println("Circle at (" + x + ", " + y + ") radius " + radius); }
}
public class TestCircle {
public static void main(String[] args) {
Circle c = new Circle(2, 3, 5);
Point p = c; // up-casting: a Circle is treated as a Point
p.show(); // calls Circle's show() (dynamic binding)
// p.area(); // not allowed: Point reference cannot see area()
Circle back = (Circle) p; // down-casting to use Circle methods again
System.out.printf("Area = %.2f%n", back.area());
}
}Q4 – Shape, Rectangle, Oval, Triangle: polymorphism
Every element of the Shape array is handled through the same calls, s.draw() and s.area(), but each object runs its own version – run-time polymorphism. Output: rectangle area 12.00, oval 6.28, triangle 12.00 (tested).
abstract class Shape {
abstract double area();
void draw() { System.out.println("Drawing a shape"); }
}
class Rectangle extends Shape {
double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
void draw() { System.out.println("Drawing a rectangle"); }
}
class Oval extends Shape {
double a, b; // semi-axes
Oval(double a, double b) { this.a = a; this.b = b; }
double area() { return Math.PI * a * b; }
void draw() { System.out.println("Drawing an oval"); }
}
class Triangle extends Shape {
double base, height;
Triangle(double base, double height) { this.base = base; this.height = height; }
double area() { return 0.5 * base * height; }
void draw() { System.out.println("Drawing a triangle"); }
}
public class Polymorphism {
public static void main(String[] args) {
Shape[] shapes = { new Rectangle(4, 3), new Oval(2, 1), new Triangle(6, 4) };
for (Shape s : shapes) { // one call, different behaviour
s.draw();
System.out.printf("Area = %.2f%n", s.area());
}
}
}Q5 – Exception handling
An exception is an event that disrupts normal flow at run time (e.g. dividing by zero). Java handles it with try (code that may fail), catch (one block per exception type), finally (always runs, used for clean-up), throw and throws. Checked exceptions (IOException) must be caught or declared; unchecked ones (ArithmeticException) need not be. The program below handles three different exceptions; with index 1 and divisor 0 it prints “Cannot divide by zero.” (tested).
import java.util.Scanner;
public class MultiCatch {
public static void main(String[] args) {
int[] marks = {70, 80, 90};
Scanner in = new Scanner(System.in);
try {
System.out.print("Enter index: ");
int i = Integer.parseInt(in.nextLine()); // NumberFormatException
System.out.print("Enter divisor: ");
int d = Integer.parseInt(in.nextLine());
System.out.println("Result = " + marks[i] / d); // ArrayIndexOutOfBounds / Arithmetic
} catch (NumberFormatException e) {
System.out.println("Please enter a whole number.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index must be 0 to " + (marks.length - 1) + ".");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Program finished.");
in.close();
}
}
}Q6 – Reading and writing mytext.txt with text streams
Character (text) streams are Reader/Writer classes. FileWriter + PrintWriter write lines; FileReader + BufferedReader read them line by line. try-with-resources closes the files automatically (tested).
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
// write text using a character (text) stream
try (PrintWriter out = new PrintWriter(new FileWriter("mytext.txt"))) {
out.println("University of Sargodha");
out.println("Object Oriented Programming");
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// read the text back line by line
try (BufferedReader in = new BufferedReader(new FileReader("mytext.txt"))) {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
}
}Q7 – Swing four-function calculator
The window has two text fields, four buttons (+, −, ×, ÷) and a result label. The frame listens to button clicks (ActionListener), reads both numbers and shows the result; it also handles invalid input and division by zero. The code compiles with javac.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private final JTextField num1 = new JTextField(8), num2 = new JTextField(8);
private final JLabel result = new JLabel("Result: ");
public Calculator() {
super("Simple Calculator");
setLayout(new FlowLayout());
add(new JLabel("First:")); add(num1);
add(new JLabel("Second:")); add(num2);
for (String op : new String[]{"+", "-", "*", "/"}) {
JButton b = new JButton(op);
b.addActionListener(this);
add(b);
}
add(result);
setSize(320, 140);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
try {
double a = Double.parseDouble(num1.getText());
double b = Double.parseDouble(num2.getText());
double r;
switch (e.getActionCommand()) {
case "+": r = a + b; break;
case "-": r = a - b; break;
case "*": r = a * b; break;
default:
if (b == 0) { result.setText("Result: cannot divide by 0"); return; }
r = a / b;
}
result.setText("Result: " + r);
} catch (NumberFormatException ex) {
result.setText("Result: enter valid numbers");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Calculator().setVisible(true));
}
}
