Java · Question paper

CET-2 · 6 Oct 2025

Object Oriented Programming using Java (C2311C1) · Continuous Evaluation Test 2 · 30 marks ITM SLS Baroda University · SOCSET · Semester 3. Question 1 is compulsory. The paper prints the date as 06/09/2025; 6 September 2025 was a Saturday and the other CET-2 papers of this batch were held 7–10 October, so it is listed here as 6 October 2025. Questions transcribed from the original paper. Solutions are written by CampusLoop; check them against your class notes. Programs were compiled and run on JDK 26.

Q1. Multiple choice questions [6]

1. Which keyword is used to call the constructor of a superclass? a) this · b) super · c) parent · d) base Answer: (b) super.

2. Which of the following stops a class from being inherited? a) static · b) final · c) private · d) const Answer: (b) final.

3. What does the instanceof operator check? a) Whether a reference is null · b) Whether an object belongs to a particular class/interface · c) Whether two objects are equal · d) Whether a method is overridden Answer: (b).

4. Which block is always executed whether or not an exception occurs? a) catch · b) throw · c) finally · d) throws Answer: (c) finally.

5. Which method pauses a thread for a specified time? a) sleep() · b) wait() · c) join() · d) suspend() Answer: (a) sleep().

6. Which interface must a class implement to create a thread without extending Thread? a) Runnable · b) Threadable · c) Executor · d) Process Answer: (a) Runnable.

Q2. Answer any 3 out of 5 (3 marks each) [9]

Q2.1 Explain method overriding and how it is used in multilevel inheritance.

Method overriding: a subclass provides its own implementation of a method already defined in its superclass, with the same name, parameters and return type (or a subtype). The call is resolved at run time on the actual object (dynamic dispatch). Rules: it cannot reduce visibility; final, static and private methods cannot be overridden; use @Override to let the compiler check.

In multilevel inheritance (A → B → C) each level can override again; the most derived version runs, and super.method() reaches the version one level up.

class Vehicle { void describe() { System.out.println("Vehicle"); } }
class Car extends Vehicle {
    @Override void describe() { System.out.println("Car"); }
}
class SportsCar extends Car {
    @Override void describe() {
        super.describe();                     // Car's version
        System.out.println("SportsCar");
    }
}

public class OverrideDemo {
    public static void main(String[] args) {
        Vehicle v = new SportsCar();          // upcast
        v.describe();
    }
}

Output: Car then SportsCar.

Q2.2 Short note on the Throwable class and the exception hierarchy.

java.lang.Throwable is the root of everything that can be thrown (throw) and caught (catch). It stores a message and a stack trace (getMessage(), printStackTrace(), getCause()).

Object
 └── Throwable
      ├── Error                      (serious JVM problems; do not catch)
      │     ├── OutOfMemoryError
      │     ├── StackOverflowError
      │     └── VirtualMachineError …
      └── Exception                  (conditions a program can handle)
            ├── IOException          ─┐
            │     └── FileNotFoundException │ checked: must be caught
            ├── SQLException          │ or declared with throws
            ├── ClassNotFoundException ┘
            └── RuntimeException     (unchecked)
                  ├── ArithmeticException
                  ├── NullPointerException
                  ├── ArrayIndexOutOfBoundsException
                  ├── ClassCastException
                  └── NumberFormatException (via IllegalArgumentException)
  • Checked exceptions are verified at compile time.
  • Unchecked exceptions (RuntimeException and Error) are not.
  • Custom exceptions extend Exception (checked) or RuntimeException (unchecked).

Q2.3 Why is multiple inheritance not supported in Java?

Java does not allow a class to extend more than one class, mainly because of the diamond problem: if B and C both extend A and override show(), and D extends both B and C, a call d.show() is ambiguous (which version?). It also complicates constructor chaining (which super() runs first) and the object layout. Leaving it out keeps the language simple and unambiguous.

Java gets most of the benefit through interfaces: a class can implement many interfaces. If two interfaces supply the same default method, the class must override it and can choose explicitly with B.super.show(), so the ambiguity is resolved by the programmer.

class A { void show() {} }
class B extends A { void show() {} }
class C extends A { void show() {} }
// class D extends B, C { }   // compile error: Java does not allow this

Q2.4 Explain thread priority and daemon threads with examples.

Priority: every thread has a priority from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), default 5 (NORM_PRIORITY), inherited from the creating thread. Set with setPriority(n), read with getPriority(). It is a hint to the scheduler: higher-priority threads tend to get CPU time first, but the actual order depends on the OS, so programs must not rely on it for correctness.

public class PriorityDemo {
    public static void main(String[] args) {
        Thread low = new Thread(() -> System.out.println("low task"));
        Thread high = new Thread(() -> System.out.println("high task"));
        low.setPriority(Thread.MIN_PRIORITY);    // 1
        high.setPriority(Thread.MAX_PRIORITY);   // 10
        System.out.println(low.getPriority() + " " + high.getPriority() + " "
                + Thread.currentThread().getPriority());   // 1 10 5
        low.start();
        high.start();
    }
}

Daemon threads run in the background (e.g. garbage collector, autosave). The JVM exits when only daemon threads are left. Mark with setDaemon(true) before start(). Example: Java end-sem 2025, Q3.6.

Q2.5 Purpose of the super keyword in inheritance, with a code snippet.

super refers to the immediate parent class: super(args) calls the parent constructor (must be the first statement), super.method() calls an overridden parent method, and super.field reaches a hidden parent field. Code and output: Java end-sem 2025, Q3.3.

Q3. Answer any 3 out of 5 (5 marks each) [15]

Q3.1 Interface Shape with area(); Circle and Rectangle through an interface reference.

interface Shape {
    double area();
}

class Circle implements Shape {
    private double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}

class Rectangle implements Shape {
    private double l, w;
    Rectangle(double l, double w) { this.l = l; this.w = w; }
    public double area() { return l * w; }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Shape s;                              // interface reference
        s = new Circle(7);
        System.out.printf("Circle area = %.2f%n", s.area());
        s = new Rectangle(5, 4);
        System.out.printf("Rectangle area = %.2f%n", s.area());
    }
}

Output:

Circle area = 153.94
Rectangle area = 20.00

Interface methods are implicitly public abstract, so the implementations must be declared public.

Q3.2 Custom exception InvalidAgeException for a driving-licence registration.

class InvalidAgeException extends Exception {          // checked custom exception
    InvalidAgeException(String msg) { super(msg); }
}

public class LicenceRegistration {
    static void register(String name, int age) throws InvalidAgeException {
        if (age < 18)
            throw new InvalidAgeException(name + " is " + age + "; minimum age is 18");
        System.out.println(name + " registered for a driving licence");
    }
    public static void main(String[] args) {
        String[] names = {"Arjun", "Kavya"};
        int[] ages = {21, 16};
        for (int i = 0; i < names.length; i++) {
            try {
                register(names[i], ages[i]);
            } catch (InvalidAgeException e) {
                System.out.println("Registration failed: " + e.getMessage());
            }
        }
    }
}

Output:

Arjun registered for a driving licence
Registration failed: Kavya is 16; minimum age is 18

throw raises the exception, throws declares it on the method, and try/catch handles it in main.

Q3.3 Differentiate between abstract class and interface with example.

Comparison table and program: Java end-sem 2025, Q2.6. Key points: an abstract class can have state, constructors and concrete methods and is extended once; an interface holds constants and abstract/default/static methods and a class can implement many.

Q3.4 Product, FlipCart, Amazon and Product_app.

class Product {
    private int id;
    private String name;
    protected double price;
    static int count = 0;                       // number of Product objects

    Product(int id, String name, double price) {
        this.id = id; this.name = name; this.price = price;
        count++;
    }
    void display() {
        System.out.println("ID " + id + ", " + name + ", price " + price);
    }
}

class FlipCart extends Product {
    FlipCart(int id, String name, double price) { super(id, name, price); }
    @Override
    void display() {
        System.out.print("[FlipCart] ");
        super.display();
    }
}

class Amazon extends Product {
    double discount;
    Amazon(int id, String name, double price) { super(id, name, price); }
    void calculate_discount() {
        discount = price > 5000 ? price * 0.10 : price * 0.05;
    }
    @Override
    void display() {
        System.out.print("[Amazon] ");
        super.display();
        System.out.println("   discount " + discount + ", pay " + (price - discount));
    }
}

public class Product_app {
    public static void main(String[] args) {
        Product[] items = {
            new FlipCart(1, "Headphones", 2499),
            new Amazon(2, "Smartwatch", 7999),
            new Amazon(3, "Keyboard", 1200),
            new FlipCart(4, "Monitor", 10999)
        };
        for (Product p : items) {
            if (p instanceof Amazon)
                ((Amazon) p).calculate_discount();   // downcast through the Product reference
            p.display();                            // overridden version runs
        }
        System.out.println("Products created: " + Product.count);
    }
}

Output:

[FlipCart] ID 1, Headphones, price 2499.0
[Amazon] ID 2, Smartwatch, price 7999.0
   discount 799.9000000000001, pay 7199.1
[Amazon] ID 3, Keyboard, price 1200.0
   discount 60.0, pay 1140.0
[FlipCart] ID 4, Monitor, price 10999.0
Products created: 4

calculate_discount() exists only in Amazon, so a Product reference needs an instanceof check and a cast to call it. (The long decimal is ordinary floating-point rounding; use printf("%.2f") to show 799.90.)

Q3.5 Write the output of the programs.

Constructor chaining (A → B → C):

class A { A() { System.out.println("Class A Constructor"); } }
class B extends A {
    B() { super(); System.out.println("Class B Constructor"); }
}
class C extends B {
    C() { System.out.println("Class C Constructor"); }
}
public class Test {
    public static void main(String[] args) { C obj = new C(); }
}

Output:

Class A Constructor
Class B Constructor
Class C Constructor

C's constructor implicitly calls super() first, so constructors run from the top of the hierarchy down.

Abstract class and dynamic dispatch: Animal a = new Dog(); a.sound(); prints Bark, then a = new Cat(); a.sound(); prints Meow: the overridden method of the actual object runs.

Exception not caught:

public class Example {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            System.out.println(a / b);
        } catch (NullPointerException e) {
            System.out.println("Null Pointer Exception");
        } finally {
            System.out.println("Finally Executed");
        }
        System.out.println("End of Program");
    }
}

Output:

Finally Executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Example.main(Example.java:5)

a / b throws ArithmeticException, which the NullPointerException catch does not match. finally still runs, then the exception propagates out of main and the program terminates, so "End of Program" is not printed.