Exam Kit Assignment Solutions

Assignment Solutions

Read this first: you are not being marked on these assignments here. They matter because 11 of the 15 questions are also exam questions.

So this page answers them at exam length — the same answers you'd write on the paper — not at "submission length".

Java version: all code targets Java 25 LTS (2025) and also compiles on Java 21 and Java 17.


Why these 15 questions matter

Assignment Questions Also an exam question?
1 Compiler vs interpreter, OOP features, class vs object, operators, tokens & types 4 of 5 — class vs object is asked twice over
2 Multiple inheritance, interface, constructor, overriding rules, super/subclass 5 of 5 — all of them
3 Collections, packages, threads, thread life cycle, try-catch-finally 2 of 5 fully, 3 partly

Assignment 3 is the one to read twice. It covers Collections and Threads — the two topics your PPT deck never taught. If you only revise from the slides, you walk in blind on those.


Assignment 1


A1-Q1 · Compiler vs Interpreter

In plain words: Both turn your code into something the computer can run. The difference is when and how much.

Think of a translator. A compiler translates the whole book before you read it. An interpreter translates one sentence at a time while you read.

Compiler Interpreter
Translates the whole program first Translates line by line
Creates a file (.class) Creates no file
Runs faster afterwards Runs slower
Reports all errors at once Stops at the first error
C, C++, Java Python, JavaScript

Where Java sits — this is the part that earns the extra mark:

Java uses both. javac compiles your code into bytecode, and then the JVM interprets that bytecode.

Hello.java --javac--> Hello.class --JVM--> output

So the honest answer is: "Java is both compiled and interpreted."

If you remember one thing: Java compiles to bytecode, then interprets it.


A1-Q2 · Features of an object-oriented language

In plain words: OOP gives you four big ideas, plus a few useful extras.

The four pillars:

Feature In plain words Java keyword
Encapsulation Hide the data private
Inheritance Borrow from a parent extends
Polymorphism One name, many behaviours overloading / overriding
Abstraction Show the button, hide the wiring abstract

Other features worth naming: classes and objects · message passing (calling each other's methods) · reusability · data hiding · modularity.

If you remember one thing: always lead with the four pillars. They're what the examiner is looking for.


A1-Q3 · Difference between a class and an object

In plain words: A class is the plan. An object is the thing.

Class Object
The blueprint The real item
No memory Memory in the heap
Written once Many can exist
class Car { } Car c = new Car();
class Car {
    String model;
    void show() { System.out.println(model); }
}
public class Main {
    public static void main(String[] args) {
        Car c1 = new Car();
        c1.model = "Nexon";
        Car c2 = new Car();
        c2.model = "i20";
        c1.show();          // Nexon
        c2.show();          // i20
    }
}

If you remember one thing: one blue print, many houses.


A1-Q4 · Types of operators in Java

In plain words: A symbol that does something to values.

Family Symbols Example
Arithmetic + - * / % 10 % 3 → 1
Relational == != > < >= <= 5 > 3 → true
Logical && \|\| ! true && false → false
Bitwise & \| ^ ~ 5 & 3 → 1
Assignment = += -= *= a += 5
Unary ++ -- a++
Ternary ? : (a>b) ? a : b
public class Main {
    public static void main(String[] args) {
        int a = 10, b = 3;
        System.out.println(a + b);      // 13
        System.out.println(a / b);      // 3   <- decimals dropped
        System.out.println(a % b);      // 1
        System.out.println(a > b);      // true
        System.out.println(5 & 3);      // 1
        System.out.println((a > b) ? a : b);   // 10
    }
}

If you remember one thing: 10 / 3 is 3, because both are whole numbers.


A1-Q5 · Java tokens and data types

In plain words: A token is the smallest meaningful piece of a program — like a word in a sentence.

The tokens:

Token Examples
Keywords class, int, new, if, return
Identifiers Student, main, rollNo
Literals 10, 3.14, 'A', "Hi", true
Operators + - * / = ==
Separators ( ) { } [ ] ; ,

The data types: 8 primitives — byte, short, int, long, float, double, char, boolean. Everything else (String, arrays, your own classes) is an object.

If you remember one thing: tokens are the words; data types are the kinds of values those words can hold.


Assignment 2


A2-Q1 · Multiple inheritance for area of circle and square

In plain words: Java won't let a class have two parents. But it will let a class implement two interfaces — and that's how you get multiple inheritance.

Think of a person who is both a teacher and a musician. Not two parents — two roles, one person.

interface Shape {
    double area();
}
interface Measurable {
    double perimeter();
}

// Circle has BOTH roles
class Circle implements Shape, Measurable {
    double r;
    Circle(double r) { this.r = r; }
    public double area()      { return Math.PI * r * r; }
    public double perimeter() { return 2 * Math.PI * r; }
}

// Square also has both
class Square implements Shape, Measurable {
    double side;
    Square(double side) { this.side = side; }
    public double area()      { return side * side; }
    public double perimeter() { return 4 * side; }
}

public class Main {
    public static void main(String[] args) {
        Circle c = new Circle(7);
        Square s = new Square(5);

        System.out.printf("Circle area = %.2f%n", c.area());
        System.out.printf("Circle perimeter = %.2f%n", c.perimeter());
        System.out.println("Square area = " + s.area());
        System.out.println("Square perimeter = " + s.perimeter());
    }
}
Circle area = 153.94
Circle perimeter = 43.98
Square area = 25.0
Square perimeter = 20.0

Write this sentence too: "Java does not allow multiple inheritance with classes because of the diamond problem — if two parents had the same method, Java wouldn't know which body to use. Interfaces have no method bodies, so there is no confusion."

If you remember one thing: implements A, B is how Java does multiple inheritance.


A2-Q2 · Interface with an example

In plain words: An interface is a contract — a list of methods a class promises to provide. It says what, never how.

Think of a job advert: "must know Java, must know SQL". Two different people can both fit it and do the work completely differently.

interface Animal {
    void sound();
    void eat();
}

class Dog implements Animal {
    public void sound() { System.out.println("bark"); }
    public void eat()   { System.out.println("bones"); }
}

class Cat implements Animal {
    public void sound() { System.out.println("meow"); }
    public void eat()   { System.out.println("milk"); }
}

public class Main {
    public static void main(String[] args) {
        Animal a;
        a = new Dog(); a.sound(); a.eat();
        a = new Cat(); a.sound(); a.eat();
    }
}
bark
bones
meow
milk

The rules: no new on an interface · methods are public abstract by default · variables are public static final · no constructors · a class can implement many.

If you remember one thing: an interface is a promise; the class keeps it.


A2-Q3 · Constructor, and how objects are constructed

In plain words: A constructor is the setup code that runs the moment an object is made.

What happens when you write new Student(101, "Aarav"):

  1. Java loads the Student class
  2. Java reserves memory on the heap; every field gets a default (0, null)
  3. The parent constructor runs first
  4. Then the constructor body fills in your values
  5. Java hands you back the address of the object

Constructor overloading means several constructors, each taking different inputs.

class Cube {
    double w, h, d;

    Cube(double w, double h, double d) {   // the one that does the work
        this.w = w; this.h = h; this.d = d;
    }
    Cube(double side) { this(side, side, side); }   // a perfect cube
    Cube() { this(1, 1, 1); }                       // a 1x1x1 box

    double volume() { return w * h * d; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Cube().volume());          // 1.0
        System.out.println(new Cube(5).volume());         // 125.0
        System.out.println(new Cube(2, 3, 4).volume());   // 24.0
    }
}

If you remember one thing: this(...) must be the first line.


A2-Q4 · Method overriding and its rules

In plain words: The child writes its own version of a method the parent already has — same name, same inputs.

class Animal {
    void sound() { System.out.println("some sound"); }
}
class Dog extends Animal {
    @Override
    void sound() { System.out.println("dog barks"); }
}
public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();       // dog barks
    }
}

The rules — learn these, the question asks for them specifically:

# Rule
1 Same method name
2 Same parameters
3 Same return type (or a subtype)
4 Cannot reduce the access level
5 final methods cannot be overridden
6 static methods cannot be overridden — only hidden
7 private methods cannot be overridden
8 Constructors cannot be overridden
9 Cannot throw broader checked exceptions
10 Use @Override so the compiler checks you

If you remember one thing: rules 4 and 9 are the two most people forget.


A2-Q5 · Superclass and subclass

In plain words: The superclass is the parent — it holds the shared stuff. The subclass is the child — it inherits that and adds its own.

Think of a Vehicle superclass with start(), and a Bike subclass that inherits start() and adds ride().

class Employee {
    String name;
    Employee(String name) { this.name = name; }

    double salary() { return 30000; }
    void show() {
        System.out.println(name + " earns " + salary());
    }
}

class Manager extends Employee {
    double bonus;
    Manager(String name, double bonus) {
        super(name);
        this.bonus = bonus;
    }
    @Override
    double salary() { return 30000 + bonus; }
}

public class Main {
    public static void main(String[] args) {
        Employee[] staff = { new Employee("Aarav"), new Manager("Riya", 15000) };
        for (Employee e : staff) e.show();
    }
}
Aarav earns 30000.0
Riya earns 45000.0

Notice: the loop doesn't know or care which kind each one is. That's inheritance and polymorphism working together.

If you remember one thing: extends gives an IS-A relationship. A Manager is an Employee.


Assignment 3

⚠️ Q1 and Q3/Q4 have no slides behind them. Collections and Threads are not in your PPT deck. Read these twice.


A3-Q1 · What is a Java Collection?

In plain words: A collection is a smart box that can grow and shrink. An array can't — you must decide its size up front and live with it.

Think of an array as an egg carton (12 slots, fixed). A collection is a shopping bag (throw things in, take things out).

Interface Think of it as Duplicates? Order?
List A shopping list Yes Yes
Set A guest list No No
Map A phone book Keys unique Depends

Say this out loud in the exam: "Map is not a Collection. It stores key-value pairs, so it sits on its own branch."

import java.util.*;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java"); list.add("Python"); list.add("Java");
        System.out.println("List  : " + list);          // duplicate kept

        HashSet<String> set = new HashSet<>(list);
        System.out.println("Set   : " + set);           // duplicate gone

        TreeSet<Integer> sorted = new TreeSet<>();
        sorted.add(5); sorted.add(1); sorted.add(9); sorted.add(1);
        System.out.println("Sorted: " + sorted);        // sorted, no dupes

        HashMap<Integer, String> map = new HashMap<>();
        map.put(101, "Aarav");
        map.put(101, "Replaced");                       // same key overwrites
        System.out.println("Map   : " + map);
    }
}
List  : [Java, Python, Java]
Set   : [Java, Python]
Sorted: [1, 5, 9]
Map   : {101=Replaced}

If you remember one thing: List keeps order, Set blocks duplicates, Map looks things up by key.


A3-Q2 · What is a package? Benefits and steps

In plain words: A package is a folder for classes. It keeps related classes together and stops name clashes.

Think of a filing cabinet. You could pile every paper on one desk — but two people named "Rahul Sharma" would get mixed up.

Benefits: no name clashes · groups related classes · controls access · reusable · easier to maintain.

Built-in packages you already use:

Package Contains
java.lang String, Math, System — imported automatically
java.util ArrayList, HashMap, Scanner
java.io file reading and writing

Steps to make your own:

  1. Write package mypack; as the very first line
  2. Compile with javac -d . MyClass.java — this creates the mypack/ folder
  3. Write import mypack.MyClass; where you need it
  4. Run with java -cp . Main

If you remember one thing: the -d . is what creates the folder. Without it, the package doesn't exist.


A3-Q3 · Thread states, properties and synchronization

In plain words: A thread is one small worker inside your program. Several can work at the same time.

The six states (Java really has six — not five):

State What's happening
NEW Created, not started
RUNNABLE Ready, or running right now
BLOCKED Waiting for a lock
WAITING Waiting indefinitely (wait(), join())
TIMED_WAITING Waiting with a timer (sleep(1000))
TERMINATED Finished — cannot restart

Properties: name · priority (1–10, default 5, only a hint) · daemon flag · alive · state.

Synchronization stops two threads trampling each other.

Think of a single-stall washroom. The lock means only one person is inside at a time. Without the lock, two people walk in and everything goes wrong.

class Counter {
    private int count = 0;
    public synchronized void inc() { count++; }    // the lock
    public int get() { return count; }
}

class Worker implements Runnable {
    Counter c;
    Worker(Counter c) { this.c = c; }
    public void run() {
        for (int i = 0; i < 100000; i++) c.inc();
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Counter c = new Counter();
        Thread t1 = new Thread(new Worker(c));
        Thread t2 = new Thread(new Worker(c));
        t1.start(); t2.start();
        t1.join();  t2.join();
        System.out.println(c.get());     // 200000, always
    }
}

Delete synchronized and the number comes out lower, differently each run. That's a race condition — mention it and you've written a better answer.

If you remember one thing: without synchronized, two threads lose each other's updates.


A3-Q4 · Thread life cycle with a diagram

In plain words: A thread is born, waits its turn, runs, sometimes pauses, then dies.

Draw this:

      NEW
       │  start()
       ▼
   RUNNABLE  ◄──────────┐
       │                │
       │ sleeps / waits │  timer ends
       │ waits for lock │  or notified
       ▼                │
  BLOCKED / WAITING ────┘
       │
       │ run() finishes
       ▼
   TERMINATED

The five boxes to draw: New → Runnable → Running → Blocked → Dead.

Facts that earn marks:

If you remember one thing: the diagram is worth more than the paragraph. Draw it first, then label it.


A3-Q5 · The role of try, catch and finally

In plain words: try = the risky part. catch = the safety net. finally = the cleanup that happens no matter what.

Block Job
try Hold the code that might break
catch Handle the break if it happens
finally Always run — close files, release things
public class Main {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            System.out.println(a / b);           // breaks
        } catch (ArithmeticException e) {
            System.out.println("cannot divide by zero");
        } finally {
            System.out.println("cleanup always runs");
        }
        System.out.println("program continues");
    }
}
cannot divide by zero
cleanup always runs
program continues

Rules worth stating: 1. finally runs even if try has a return 2. Specific catches come before general ones 3. Only the first matching catch runs

If you remember one thing: finally runs no matter what — that's its whole job.


The summary table

# Question Also in the exam? Read the full answer in
A1-1 Compiler vs interpreter Likely here
A1-2 OOP features Yes 04 §1.1, 07 Q9
A1-3 Class vs object Yes, twice 04 §1.3, 07 Q1
A1-4 Operators Yes 04 §2.3, 07 Q12
A1-5 Tokens and types Yes 04 §2.1, 07 Q11
A2-1 Multiple inheritance Yes 07 Q5
A2-2 Interface Yes 04 §7.2, 07 Q5
A2-3 Constructor Yes 04 §5.2, 07 Q2
A2-4 Overriding rules Yes 04 §6.3, 07 Q3
A2-5 Superclass/subclass Yes 04 §6.1, 07 Q4
A3-1 Collections Yes 03 Part A, 07 Q18
A3-2 Packages Yes 04 §7.4, 07 Q15
A3-3 Threads Yes 03 Part B, 07 Q19
A3-4 Thread life cycle Yes 03 Part B
A3-5 try-catch-finally Yes 04 §8.2, 07 Q7

14 of 15 are exam questions. That's why this page exists.