Skip to content
Unit 4 Syllabus Note· Object Oriented Programming using JAVA

Object Oriented Programming using JAVA

Comprehensive exam revision notes for BCA-201N Unit 4 (Exception Handling & Multithreaded Programming). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Object Oriented Programming using JAVA

Exception Handling & Multithreaded Programming

Core Definitions & Key Concepts

What is an 'Exception' in Java

An abnormal runtime event or condition that disrupts the normal sequential flow of program instructions. In Java, all exceptions are represented as objects subclassed from java.lang.Throwable.

The Throwable Class Hierarchy in Java

Throwable is the root class, splitting into:

  • Error: Serious environmental problems that applications should not try to catch (e.g., OutOfMemoryError, StackOverflowError).
  • Exception: Conditions that applications can reasonably handle, divided into Checked and Unchecked Exceptions.

What is the difference between Checked and Unchecked Exceptions

  • Checked Exceptions: Inherit from Exception (excluding RuntimeException). Checked at compile-time by javac; the programmer MUST handle them using try-catch or declare them using throws (e.g., IOException, SQLException).
  • Unchecked Exceptions: Inherit from RuntimeException. Checked at runtime; usually indicate logic bugs (e.g., NullPointerException, ArrayIndexOutOfBoundsException).

The role of try, catch, and finally blocks

  • try: Encloses code that might throw an exception.
  • catch: Catches and handles specific exception types.
  • finally: Encloses cleanup code (closing files, releasing database connections) that is GUARANTEED to execute whether an exception is thrown or caught.

Does the finally block ALWAYS execute

Yes, finally executes almost unconditionally, even if try contains a return statement. The only exceptions are when System.exit(0) is invoked, or if the JVM crashes due to fatal hardware or OS failure.

throw and throws in Java

  • throw: Keyword used inside a method body to explicitly throw an exception object instance (throw new IllegalArgumentException();).
  • throws: Keyword used in the method signature to declare which checked exceptions the method might propagate (void readFile() throws IOException).

What are the two ways to create a Thread in Java

  1. Extending `java.lang.Thread`: Subclass Thread and override its run() method.
  2. Implementing `java.lang.Runnable` (Preferred): Implement the functional interface Runnable, override run(), and pass its instance to new Thread(runnable).

Why is implementing Runnable preferred over extending Thread

Java supports single class inheritance. Extending Thread prevents the class from extending any other class. Implementing Runnable leaves the class free to extend other classes and promotes clean separation of task logic from thread execution.

The difference between start() and run() methods of Thread

  • start(): Allocates a new OS native execution thread, creates a private call stack, and invokes the run() method asynchronously.
  • run(): Contains the thread task code. Calling run() directly merely executes it synchronously on the current thread without spawning a new thread.

What is Thread Synchronization in Java

A mechanism that prevents race conditions by controlling concurrent access of multiple threads to shared critical resources. Implemented using the synchronized keyword (synchronized methods or synchronized blocks), which acquires an intrinsic monitor lock on the target object.

Conceptual & Architectural Analysis

The Life Cycle of a Thread in Java with State Transitions

A Java thread traverses 6 states (Thread.State enum):

System Architecture / Concept DiagramHorizontal Scroll Enabled
   +-----+       start()       +-------+
   | NEW | ------------------> | READY |
   +-----+                     +-------+
                                   |  CPU Dispatch
                                   v
                             +---------+
                             | RUNNING |
                             +---------+
                              /    |    \
            sleep()/wait()   /     |     \   yield() / quantum expire
                            v      |      v
             +------------------+  |   +-------+
             | BLOCKED/WAITING/ |  |   | READY |
             | TIMED_WAITING    |  |   +-------+
             +------------------+  |
                     | notify()    |
                     v             v run() ends
                +-------+     +------------+
                | READY |     | TERMINATED |
                +-------+     +------------+

The Try-With-Resources Statement (Java 7+ Automatic Resource Management)

Try-with-resources automatically closes any resource that implements java.lang.AutoCloseable at the end of the statement block, eliminating tedious nested finally blocks:

Java
1try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
2 String line = br.readLine();
3 System.out.println(line);
4} catch (IOException e) {
5 System.err.println("Read error: " + e.getMessage());
6}
7// br.close() is called automatically here!

Inter-Thread Communication using wait(), notify(), and notifyAll()

Declared in java.lang.Object, these methods must be called from inside a synchronized context:

  • wait(): Releases the object monitor lock and puts the calling thread into a sleeping state until signaled.
  • notify(): Wakes up a single thread waiting on the object monitor.
  • notifyAll(): Wakes up all threads waiting on the monitor lock.

What is a Custom (User-Defined) Exception and How Do You Create One

Custom exceptions represent domain-specific error conditions in business logic. Created by extending Exception (for checked) or RuntimeException (for unchecked):

Java
1class InsufficientFundsException extends Exception {
2 private double shortfall;
3 public InsufficientFundsException(double shortfall) {
4 super("Withdrawal failed! Shortfall amount: Rs. " + shortfall);
5 this.shortfall = shortfall;
6 }
7 public double getShortfall() { return shortfall; }
8}

Deadlock in Multithreading and Techniques to Avoid It

Deadlock occurs when Thread 1 holds Lock A and waits for Lock B, while Thread 2 holds Lock B and waits for Lock A. Neither thread can proceed. Prevention Strategies:

  1. Lock Ordering: Always acquire shared locks in a strict global sequential order.
  2. Lock Timeout: Use ReentrantLock.tryLock(timeout) instead of intrinsic synchronized blocks.
  3. Deadlock Detection: Monitor thread states via JConsole or thread dumps.

In-Depth Analysis & Implementation

Develop a Complete Thread-Safe Producer-Consumer Application in Java using Semaphores, wait(), and notify()

System Architecture / Concept DiagramHorizontal Scroll Enabled
/**
 * University Examination Model Solution: BCA-201N Unit 4
 * Classic Bounded-Buffer Producer-Consumer Implementation
 */
import java.util.LinkedList;
import java.util.Queue;

class SharedBuffer {
    private final Queue<Integer> queue = new LinkedList<>();
    private final int capacity;

    public SharedBuffer(int capacity) {
        this.capacity = capacity;
    }

    public synchronized void produce(int value) throws InterruptedException {
        while (queue.size() == capacity) {
            System.out.println("[Buffer Full] Producer waiting...");
            wait(); // Releases lock, sleeps until consumer consumes
        }
        queue.add(value);
        System.out.printf("Produced item: %-4d | Buffer size: %d/%d%n", value, queue.size(), capacity);
        notify(); // Wakes up consumer
    }

    public synchronized int consume() throws InterruptedException {
        while (queue.isEmpty()) {
            System.out.println("[Buffer Empty] Consumer waiting...");
            wait(); // Releases lock, sleeps until producer produces
        }
        int value = queue.remove();
        System.out.printf("Consumed item: %-4d | Buffer size: %d/%d%n", value, queue.size(), capacity);
        notify(); // Wakes up producer
        return value;
    }
}

public class ProducerConsumerDemo {
    public static void main(String[] args) {
        SharedBuffer buffer = new SharedBuffer(3);

        Thread producer = new Thread(() -> {
            int item = 1;
            try {
                while (item <= 6) {
                    buffer.produce(item++);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "Producer-Thread");

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 1; i <= 6; i++) {
                    buffer.consume();
                    Thread.sleep(400);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "Consumer-Thread");

        producer.start();
        consumer.start();
    }
}

Exception Propagation in Java with Code and Call Stack Mechanics

1. Call Stack Mechanics

When an exception is thrown, the runtime searches the current method frame for a matching catch block. If none exists, the method frame is popped off the call stack and control transfers to the caller method. This unwinding continues down the stack until a matching catch is encountered or main() terminates, causing the JVM to print a stack trace.

Java
1class ExceptionPropagationDemo {
2 void method3() {
3 int result = 50 / 0; // ArithmeticException thrown here
4 }
5 void method2() {
6 method3(); // Propagated
7 }
8 void method1() {
9 try {
10 method2();
11 } catch (ArithmeticException e) {
12 System.out.println("Handled in method1: " + e.getMessage());
13 }
14 }
15 public static void main(String[] args) {
16 new ExceptionPropagationDemo().method1();
17 }
18}

Thread Priority, Daemon Threads, and join() Synchronization in Java

1. Thread Priorities

Thread priorities range from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with default NORM_PRIORITY (5). They serve as hints to the OS thread scheduler, but do NOT guarantee exact execution order across platforms.

2. Daemon Threads

A background service provider thread (e.g., Garbage Collector). When all user (non-daemon) threads complete, the JVM halts immediately, killing any active daemon threads.

3. The join() Method

Calling t.join() causes the current calling thread to pause execution until thread t completes execution, ensuring sequential ordering among concurrent tasks.

Important Exam Points & Quick Revision

Producer-Consumer with wait() and notify() is a staple 10/15 mark exam question. Know the difference between checked and unchecked exceptions and the exact Throwable hierarchy.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Exception Handling & Multithreaded Programming.

Weak topic hint

Exception Handling & Multithreaded Programming still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.