Top Banner Ad
BCS403 · 2025-2622 Questions

Object Oriented Programming with Java — 2025-26

Section A

2 Marks Each · 7 questions
Q1a2MUnit 1 — JVM
Core Concept

State the specific functions of the JVM, JRE, and JDK. Why is the JVM the reason Java is called Platform Independent?

Bytecode is the compiled form of Java source stored in class files. It is platform neutral, unlike native machine code. The JVM reads bytecode, verifies it and translates hot sections into native instructions with a just in time compiler, allowing the same class file to run on many systems.

Key Points

  • Stored in class files
  • Platform neutral instruction set
  • Executed and optimised by the JVM
Q1b2MUnit 1 — Constructors
Core Concept

What is the role of constructors in Java classes and when are they invoked automatically?

Constructor overloading means defining several constructors in one class with different parameter lists. The compiler selects the matching constructor from the arguments supplied. It lets objects be created with default values or with full initial data, while keeping the class interface convenient and consistent.

Key Points

  • Same name, different parameters
  • Compiler chooses the match
  • Supports flexible object creation
Q1c2MUnit 2 — Use of try
Core Concept

List the five Exception Handling keywords. Can a try block exist without a catch or finally?

The five keywords are try, catch, finally, throw and throws. A try block cannot stand alone; it must be followed by at least one catch or a finally block. Try with resources is also valid because it supplies automatic cleanup without writing finally explicitly.

Key Points

  • Five exception keywords
  • Try needs catch or finally
  • Try with resources is valid
Q1d2MUnit 2 — Multithreading: Thread
Core Concept

Define a Thread. What is the difference between extending Thread and implementing Runnable?

A thread is a lightweight execution path inside a process with its own stack and program counter. Extending Thread makes the class a thread, while implementing Runnable separates the task from the thread and leaves the class free to extend another class, so Runnable is usually preferred.

Key Points

  • Thread is a lightweight path
  • Runnable separates task from thread
  • Runnable keeps inheritance free
Q1e2MUnit 3 — Diamond Syntax with Inner Anonymous Class
Core Concept

Explain the Diamond Syntax (<>) introduced in Java 7. How does it make generic code easier to write?

The diamond operator lets the compiler infer generic type arguments from the left hand side of an assignment, so the right hand side need not repeat them. It reduces verbosity and keeps generic code readable. Java nine extended it to anonymous inner classes where the inferred type is available.

Key Points

  • Compiler infers type arguments
  • Removes repeated type names
  • Extended to anonymous classes
Q1f2MUnit 4 — HashSet
Core Concept

Why does TreeSet keep elements in sorted order, while HashSet does not?

TreeSet stores elements in a balanced tree and iterates in sorted natural order or by a supplied comparator, so operations take logarithmic time. HashSet stores elements in hash buckets using hashCode and equals, gives no order guarantee and offers constant time average access.

Key Points

  • TreeSet uses a balanced tree
  • HashSet uses hashing
  • Sorted versus unordered iteration
Q1g2MUnit 5 — AOP
Core Concept

What is Aspect-Oriented Programming (AOP) and how it helps with logging without touching the main business logic?

Aspect oriented programming separates cross cutting concerns such as logging, security and transactions from business logic. An aspect packages the concern, advice is the code run, a pointcut selects where it applies and a join point is a candidate location. Spring weaves advice with proxies so business classes stay clean.

Key Points

  • Separates cross cutting concerns
  • Advice and pointcut select behaviour
  • Spring uses proxies

Section B

7 Marks Each · 5 questions
Q2a7MUnit 1 — Encapsulation
Core Concept

Discuss the four pillars of Object-Oriented Programming - Encapsulation, Abstraction, Inheritance, and Polymorphism. Also explain how they help in building reusable code.

Answer:

  1. Encapsulation: wrap data and methods in a class and restrict direct access with private fields + public getters/setters; protects invariants and hides implementation.
  2. Abstraction: expose only essential features through interfaces/abstract classes; hide complex details (e.g., List interface hides ArrayList internals).
  3. Inheritance: a subclass reuses and extends superclass fields/methods with extends; promotes code reuse and IS-A relationships.
  4. Polymorphism: one name, many forms - compile-time overloading and runtime overriding through dynamic dispatch.

The four pillars of object orientation. Encapsulation means bundling data with the methods that operate on it and hiding the representation behind an interface. In Java this is done with private fields and public getters and setters, so the class can enforce invariants such as a nonnegative age. Abstraction means exposing only the essential behaviour and hiding implementation detail, using interfaces and abstract classes; a List reference can be backed by ArrayList or LinkedList without the client knowing which. Inheritance lets a subclass reuse and extend the fields and methods of a superclass, creating an is a relationship and enabling code sharing. Polymorphism lets one name or reference denote different implementations, through overloading at compile time and overriding with dynamic dispatch at run time. Together these ideas produce modular code: encapsulation protects correctness, abstraction reduces coupling, inheritance removes duplication and polymorphism allows new variants to be added with minimal changes to existing clients. A good answer defines each pillar with a Java mechanism and a concrete example, then explains how the four work together to improve reuse and maintenance. It should also note the dangers: deep inheritance hierarchies can be fragile, getters that expose mutable fields can break encapsulation and an interface with too many methods can become hard to implement. Mentioning composition as an alternative to inheritance shows mature judgement, while keeping the focus on the four requested pillars.

Result: Together they produce modular, reusable, maintainable code: encapsulation protects data, abstraction hides detail, inheritance shares code and polymorphism generalises behaviour.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Encapsulation: private data + public API
  • Abstraction: essential behaviour only
  • Inheritance and polymorphism enable reuse
Q2b7MUnit 2 — Input /Output Basics: Byte Streams and Character Streams
Core Concept

Explain the difference between Byte Streams and Character Streams. Describe the classes used to read and write a simple text file.

Answer:

Byte streams Character streams
Handle 8-bit bytes Handle 16-bit Unicode characters
FileInputStream, FileOutputStream FileReader, FileWriter
BufferedInputStream, BufferedOutputStream BufferedReader, BufferedWriter
Suitable for binary files (images) Suitable for text files
import java.io.*;
public class FileDemo {
    public static void main(String[] args) throws IOException {
        try (FileWriter fw = new FileWriter("note.txt")) {
            fw.write("Hello Java");
        }
        try (BufferedReader br = new BufferedReader(new FileReader("note.txt"))) {
            System.out.println(br.readLine());
        }
    }
}

Output: Hello Java

Choosing the right stream class. The java.io package separates streams by the unit of data they transfer. Byte streams move raw eight bit values and are the correct choice for binary files such as photographs, audio, zip archives and serialised objects. Their abstract roots are InputStream and OutputStream, with commonly used concrete classes FileInputStream, FileOutputStream, BufferedInputStream and BufferedOutputStream. Character streams move Unicode characters and are the correct choice for text because they handle encoding and decoding. Their abstract roots are Reader and Writer, with FileReader, FileWriter, BufferedReader and BufferedWriter as common implementations. Reading a text file line by line with a BufferedReader is both simpler and more correct than reading bytes and decoding them by hand, because the reader handles line separators and character sets. A buffered wrapper reduces the number of system calls by reading or writing larger blocks, and try with resources guarantees that the file handle is closed even if an exception occurs. A good answer tabulates the differences, names the root classes and representative subclasses, writes a short program that writes a line to a file with FileWriter and reads it with BufferedReader, and states why text should use character streams. Mentioning that wrapping a byte stream in an InputStreamReader or OutputStreamWriter allows an explicit charset such as UTF eight shows how the two families can be combined. Noting that streams are sequential and must be closed completes the practical guidance.

Result: Use character streams for text (automatic encoding) and byte streams for binary data; try-with-resources closes them safely.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Byte vs character stream classes
  • FileReader/FileWriter for text
  • Example writes and reads Hello Java
Q2c7MUnit 3 — Records
Core Concept

Describe Sealed Classes and Records in detail. How do these features improve data modeling in Java?

Answer: Sealed classes restrict permitted subtypes: sealed interface Shape permits Circle, Rect; implementors must be final, sealed or non-sealed. They create closed hierarchies that allow exhaustive pattern matching.

sealed interface Shape permits Circle, Rect {}
final class Circle implements Shape { double r; }
final class Rect implements Shape { double l, b; }
record Point(int x, int y) {}

Records are transparent carriers: record Point(int x, int y) {} automatically provides private final fields, a canonical constructor, accessors x()/y()x()/y(), equals, hashCode and toString.

Closed hierarchies and compact data carriers. Sealed classes and records are Java features that improve data modelling by making intent explicit. A sealed class or interface uses the permits clause to name the only types allowed to extend or implement it. Every permitted subclass must be declared final, sealed or non sealed, which tells the compiler whether the hierarchy continues, is closed at that branch or is deliberately open. Because the set of variants is known, a pattern matching switch over a sealed type can be checked for exhaustiveness, so adding a new variant causes the compiler to flag every switch that must handle it. A record is a transparent carrier for immutable data. Declaring record Point with two integer components automatically generates private final fields, a canonical constructor, accessor methods named like the components, and sensible equals, hashCode and toString implementations. This removes the boilerplate that would otherwise fill a small data class. Records can implement interfaces, can have additional methods and can validate values in a compact constructor, but they cannot extend another class because they already extend Record. Together the two features support algebraic data type style modelling: a sealed interface Shape with permitted Circle and Rectangle implementations, where each implementation may be a record carrying its own fields. A good answer explains both features, gives code for a sealed interface and a record, states the rules for permitted subclasses and describes how compile time exhaustiveness and reduced boilerplate improve correctness. Mentioning that records are best for shallow immutable data while ordinary classes suit mutable or deeply hierarchical state adds depth.

Result: Records remove boilerplate for immutable data carriers and sealed classes make the set of variants explicit, giving better compile-time checking and data modelling.

x()/y()x()/y()
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Sealed permits restricts subclasses
  • Record auto-generates constructor/accessors/equals/hashCode/toString
  • Closed hierarchies + immutable carriers improve modelling
Q2d7MUnit 4 — Hierarchy of Collection Framework
Core Concept

Give a detailed description of the Java Collection Framework hierarchy. Also explain the relationship between the Iterable, Collection, and List interfaces.

Answer: The Java Collections Framework is a hierarchy of interfaces and implementations:

  1. Iterable (root): enables for-each and provides iterator().
  2. Collection extends Iterable: general contract with add, remove, size, contains.
  3. List (ordered, duplicates): ArrayList, LinkedList, Vector, Stack.
  4. Set (unique): HashSet, LinkedHashSet, TreeSet (SortedSet/NavigableSet).
  5. Queue/Deque: LinkedList, ArrayDeque, PriorityQueue.
  6. Map (key-value, separate hierarchy): HashMap, LinkedHashMap, TreeMap, Hashtable.

The framework behind Java collections. The Java Collections Framework is a coherent hierarchy of interfaces, implementations and algorithms for groups of objects. At the root is Iterable, which provides an iterator and enables the enhanced for loop. Collection extends Iterable and declares general operations such as add, remove, size, contains and clear. Its main branches are List, Set and Queue. A List is an ordered sequence that allows duplicate elements and indexed access; ArrayList and LinkedList are common implementations. A Set rejects duplicates; HashSet uses hashing, LinkedHashSet preserves insertion order and TreeSet keeps elements sorted. A Queue holds elements for processing, with Deque supporting insertion and removal at both ends and PriorityQueue ordering by priority. Map is a separate hierarchy rather than a subtype of Collection because it stores key value pairs; HashMap, LinkedHashMap and TreeMap are the common choices. Programmers should declare variables using the most general interface that supports the needed operations, so the implementation can be changed later without changing client code. A List can contain the same value twice, a Set cannot, and a Map associates a unique key with one value. A good answer draws or describes the hierarchy, explains the relationship between Iterable, Collection and List, contrasts List, Set and Map in a table and gives short code snippets showing duplicates in a list, uniqueness in a set and lookup by key in a map. Mentioning that algorithms such as sort and binarySearch are provided as static methods and that implementations have different time complexities shows practical understanding.

Result: Iterable -> Collection -> {List, Set, Queue}; Map is a parallel root for key-value pairs. The hierarchy lets code program to interfaces and swap implementations.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Iterable root, Collection extends it
  • List/Set/Queue under Collection; Map separate
  • Implementations ArrayList, HashSet, HashMap etc.
Q2e7MUnit 5 — Spring Core Basics-Spring Dependency Injection concepts
Core Concept

Explain Dependency Injection with a real-world example. How does Spring's Inversion of Control container manage these dependencies?

Answer: Dependency Injection (DI) supplies an object's collaborators from outside instead of the object creating them. Inversion of Control (IoC) is the principle that the framework, not the application code, controls object creation and wiring. Real-world example: a Chef (service) needs a Knife (dependency). Instead of the chef manufacturing a knife, the kitchen supplies one; swapping the knife does not change the chef.

interface Knife { void cut(); }
@Component class Chef {
    private final Knife knife;
    @Autowired Chef(Knife knife) { this.knife = knife; } // constructor injection
    void cook() { knife.cut(); }
}
  1. Spring's IoC container reads configuration/annotations, instantiates beans, injects dependencies, manages scope and lifecycle.
  2. Because Chef only knows the Knife interface, a different bean can be injected without changing Chef.

Supplying collaborators from outside. Dependency injection is the practice of giving an object the other objects it needs instead of letting the object construct them itself. The dependency is passed in through a constructor, a setter method or a field annotated for injection. Constructor injection is preferred because it makes required dependencies explicit, allows fields to be final and guarantees a fully initialised object. Setter injection is useful for optional dependencies, while field injection is concise but hides requirements and makes testing harder. Inversion of control is the broader principle behind this: the framework, not application code, decides when objects are created, how they are wired and when they are destroyed. Spring implements inversion of control with its IoC container. It reads configuration or annotations, discovers beans, instantiates them, injects dependencies, applies scopes and lifecycle callbacks and hands ready beans to the application. A chef and knife analogy makes the idea clear: the chef does not manufacture the knife, the kitchen supplies it, so the knife can be replaced without changing the chef. A simple Spring example declares a service component with a constructor parameter for a repository component; Spring resolves and passes the repository automatically. CRUD endpoints in a REST controller can use an injected service backed by a thread safe list storage to expose create, read, update and delete operations. A good answer defines both terms, describes the injection types, gives the real world analogy, explains the container steps and notes that injection improves testability and loose coupling. Mentioning that interfaces should be injected rather than concrete classes where possible makes substitution easier.

Result: DI is the mechanism; IoC is the container-driven control reversal that applies it.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • DI supplies dependencies externally
  • IoC container creates and wires beans
  • Chef/Knife example with @Autowired constructor

Section C

7 Marks Each · 10 questions
Q3a7MUnit 1 — Overriding
Core Concept

Explain the concept of Method Overriding. How does Java decide which method to call at runtime when a subclass object is assigned to a superclass reference?

Answer: Method overriding occurs when a subclass provides its own implementation of a superclass method with the same signature (same name, parameters and compatible return type).

class Animal { void sound() { System.out.println("animal sound"); } }
class Dog extends Animal {
    @Override void sound() { System.out.println("bark"); }
}
public class Demo {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
    }
}

Output: bark Reason: Java uses dynamic method dispatch: the reference type (Animal) decides which method is callable at compile time, but the actual object class (Dog) decides which implementation runs at runtime. static, private and final methods cannot be overridden.

Dynamic method dispatch in practice. Method overriding occurs when a subclass declares a method with the same name, parameter list and compatible return type as a method in its superclass. The at sign Override annotation asks the compiler to check that an override really happened, catching misspellings and signature mistakes. When a subclass object is assigned to a superclass reference, the reference type determines which members are visible at compile time, but the class of the object referred to determines which overridden implementation is invoked at run time. Thus Animal a = new Dog followed by a.sound calls the Dog version if Dog overrides sound. This is dynamic binding or late binding and is the mechanism behind runtime polymorphism. The rules are precise: an instance method must be inherited to be overridden; static, private and final methods cannot be overridden; the overriding method cannot reduce access; and it cannot throw broader checked exceptions. Covariant return types are allowed, so an override may return a subtype of the original return type. Calling an overridden method from a superclass constructor is dangerous because the subclass fields may not yet be initialised. A good answer states the definition, gives a complete Animal and Dog example, explains the compile time and runtime decisions separately, lists the rules and mentions the Override annotation. Mentioning that method overloading is resolved at compile time while overriding is resolved at run time makes the contrast clear and completes the explanation.

Result: a.sound() calls Dog's version because virtual dispatch chooses the runtime object's override.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Override = same signature in subclass
  • @Override annotation and rules
  • Dynamic dispatch chooses runtime object's method
Q3b7MUnit 1 — Packages: Defining Package
Core Concept

Explain how packages are defined and used in Java. Discuss the naming conventions for avoiding package name conflicts.

Answer: A package is a namespace that groups related classes and controls access; it is declared with package at the top of the file and imported with import.

// file: com/example/util/Maths.java
package com.example.util;
public class Maths { public static int square(int x) { return x*x; } }

// file: Main.java
import com.example.util.Maths;
public class Main {
    public static void main(String[] args) { System.out.println(Maths.square(6)); }
}

Output: 36 Naming: use reverse domain names (com.company.project.module), all lowercase, to avoid clashes; set CLASSPATH to the root directory containing the package folders; jar cf lib.jar com bundles a library package.

Namespaces, access and libraries. A Java package is a namespace that groups related classes and interfaces and controls access across those groups. It is declared with the package statement as the first non comment line of a source file, and the file must be stored in a matching directory path. Other classes use the import statement to refer to packaged classes by simple name, or they can use fully qualified names. Packages prevent name collisions: two classes both called Date can coexist in java.util and java.sql. They also provide access control: public members are visible everywhere, protected members are visible in the same package and in subclasses, default access is limited to the same package, and private members are visible only inside the class. Naming conventions use the reversed domain of the organisation, all in lower case, for example com.example.project.module, because a domain name is globally unique. Java does not rely on the file system alone; the classpath tells the compiler and runtime where to find compiled package roots, and jar archives bundle many packages into one library. A good answer explains how to define a package, where to place the file, how to import it, how naming avoids clashes and how access levels interact with packages. Mentioning that classes in the same package share package private access and that a jar manifest can declare an entry point shows practical understanding. A small Maths utility example imported by a Main class illustrates the mechanics clearly.

Result: Packages prevent name conflicts, control visibility and organise code into reusable libraries.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • package declaration and import
  • Reverse-domain naming avoids collisions
  • CLASSPATH points to package root; JAR bundles packages
Q4a7MUnit 2 — In-built and User Defined Exceptions
Core Concept

Create a Custom Exception class named InvalidPasswordException. Write a program that throws this exception if a user's password is less than 8 characters long.

Answer:

class InvalidPasswordException extends Exception {
    InvalidPasswordException(String msg) { super(msg); }
}
public class PasswordCheck {
    static void validate(String pwd) throws InvalidPasswordException {
        if (pwd.length() &lt; 8) throw new InvalidPasswordException("Password must be at least 8 characters");
        System.out.println("Password accepted");
    }
    public static void main(String[] args) {
        try { validate("abc"); }
        catch (InvalidPasswordException e) { System.out.println(e.getMessage()); }
    }
}

Output: Password must be at least 8 characters

Creating an exception for a domain rule. Java allows a programmer to define an exception class that expresses an application specific error. The usual pattern is to extend Exception for a checked exception, or RuntimeException for an unchecked one, and to provide a constructor that passes a message to the superclass. A password validator is a good example: the rule that a password must be at least eight characters is a business rule, not a language error, so an InvalidPasswordException communicates the failure clearly. The validate method checks the length and throws a new exception object with a helpful message. Because the exception is checked, the method declares throws InvalidPasswordException and every caller must either catch it or propagate it. In main, a try block calls validate and a catch block prints getMessage, giving a precise diagnostic instead of a stack trace. A good answer writes the exception class, the validating method and the demonstration program, explains why the exception is checked, and shows the expected output for a short password. It should mention that exception classes are ordinary classes and may carry extra fields, such as the rejected value or an error code, and that they should be named with the Exception suffix. Mentioning that overusing custom exceptions for ordinary control flow is poor practice adds judgement. A note that the message should be meaningful to the user, not just to the developer, completes the answer.

Result: A user-defined checked exception extends Exception; throw raises it and the caller catches it with a meaningful message.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Custom exception extends Exception
  • throw when length < 8
  • Output: Password must be at least 8 characters
Q4b7MUnit 2 — Inter-thread Communication
Core Concept

Write a Java program to solve the Producer-Consumer problem using a shared buffer and methods - wait() and notify().

Answer:

import java.util.*;
class Buffer {
    private final Queue<Integer> q = new LinkedList&lt; >();
    private final int CAP = 3;
    synchronized void put(int x) throws InterruptedException {
        while (q.size() == CAP) wait();
        q.add(x);
        System.out.println("Produced " + x);
        notifyAll();
    }
    synchronized int take() throws InterruptedException {
        while (q.isEmpty()) wait();
        int x = q.remove();
        System.out.println("Consumed " + x);
        notifyAll();
        return x;
    }
}
public class PC {
    public static void main(String[] args) throws InterruptedException {
        Buffer b = new Buffer();
        Thread p = new Thread(() -> {
            for (int i = 1; i &lt;= 5; i++) {
                try { b.put(i); } catch (InterruptedException e) { return; }
            }
        });
        Thread c = new Thread(() -> {
            for (int i = 1; i &lt;= 5; i++) {
                try { b.take(); } catch (InterruptedException e) { return; }
            }
        });
        p.start(); c.start(); p.join(); c.join();
    }
}

Output (typical): Produced 1 / Consumed 1 / Produced 2 / Consumed 2 / ... (order varies but never consumes empty or overflows).

Coordinating a shared buffer. The producer consumer problem has two roles: a producer creates items and places them in a bounded buffer, while a consumer removes and processes them. The buffer must never be written when full and never read when empty, and updates must be mutually exclusive. Java solves this with synchronized methods and the wait and notify mechanisms. A producer enters a synchronized put method and waits in a while loop while the queue is at capacity. When space is available it adds the item, prints a confirmation and calls notifyAll so a waiting consumer can proceed. A consumer enters a synchronized take method, waits in a while loop while the queue is empty, removes an item, prints it and calls notifyAll so a blocked producer can resume. The while loop is essential because a thread may wake spuriously or find that another thread has changed the condition first. Starting a producer and a consumer thread and joining them produces an interleaved but safe sequence of produced and consumed items. A good answer explains the roles, writes the Buffer class with both synchronized methods, writes the main method that starts the threads and explains the role of each wait and notify call. It should mention that notifyAll is safer than notify when both producers and consumers can wait on the same monitor, and that java.util.concurrent.BlockingQueue provides a library based solution. Mentioning that synchronisation prevents both lost updates and inconsistent buffer state gives the core reason.

Result: wait() blocks producer when full and consumer when empty; notifyAll() wakes the other side.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Shared bounded buffer with synchronized methods
  • while loop around wait()
  • notifyAll after put/take; no overflow or underflow
Q5a7MUnit 3 — Functional Interfaces
Predicted

What is a Functional Interface in Java? Write a program that uses Lambda Expressions to perform basic arithmetic operations (Add, Sub, Mul) via a custom Functional Interface.

Answer: A functional interface has one abstract method and can be implemented by a λ\lambda.

@FunctionalInterface
interface Calc { int operate(int a, int b); }
public class LambdaCalc {
    public static void main(String[] args) {
        Calc add = (a, b) -> a + b;
        Calc sub = (a, b) -> a - b;
        Calc mul = (a, b) -> a * b;
        System.out.println(add.operate(8, 3));
        System.out.println(sub.operate(8, 3));
        System.out.println(mul.operate(8, 3));
    }
}

Output: 11 5 24

A single method contract for lambdas. A functional interface is an interface with exactly one abstract method. It may also contain default and static methods and methods overridden from Object, but only one abstract contract remains to be implemented. The at sign FunctionalInterface annotation is optional but valuable because the compiler rejects the interface if a second abstract method is added. The single abstract method is the target type for a λ\lambda expression, whose compact syntax is parameters followed by an arrow and either an expression body or a block body. Java supplies many built in functional interfaces in java.util.function: Predicate tests a value, Function maps one value to another, Consumer performs an action, Supplier produces a value and BiFunction handles two arguments. Runnable and Comparator are older examples. Because a λ\lambda has no name and no separate class declaration, it removes a large amount of boilerplate while keeping static type checking. AλA \lambda can capture effectively final local variables from its enclosing scope, which makes callbacks concise. A good answer defines the interface rule, lists common built in examples, explains λ\lambda syntax and writes a program using Predicate and Function with printed results. It should also show a custom interface such as Calc with an operate method implemented by three lambdas for addition, subtraction and multiplication. Mentioning that lambdas are not closures over mutable variables, because captured locals must be effectively final, and that the JVM implements them with invokedynamic, shows deeper understanding while staying focused on the examination requirement.

Result: The custom functional interface Calc is implemented three times by lambdas for add, subtract and multiply.

λ\lambda AλA \lambda
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • @FunctionalInterface with one abstract method
  • Lambdas (a,b)->a+b etc.
  • Output 11, 5, 24
Q5b7MUnit 3 — Stream API
Core Concept

What is Stream API? Use the Stream API to process a list of Employee objects: filter those with salary > 50000, and print their names in uppercase.

Answer: The Stream API supports functional-style, declarative processing of sequences of data: filter -> map -> terminal operation. Streams do not store data and are lazily evaluated.

import java.util.*;
class Employee {
    String name; double salary;
    Employee(String n, double s) { name = n; salary = s; }
}
public class StreamEmp {
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(
            new Employee("Asha", 60000), new Employee("Ravi", 45000),
            new Employee("Meena", 72000));
        list.stream()
            .filter(e -> e.salary > 50000)
            .map(e -> e.name.toUpperCase())
            .forEach(System.out::println);
    }
}

Output: ASHA MEENA

Declarative processing with streams. The Stream API introduced in Java eight processes sequences of elements in a functional style. A stream pipeline begins with a source such as a collection, array or generator, continues with zero or more intermediate operations and ends with one terminal operation. Intermediate operations such as filter, map, sorted, distinct and limit are lazy: they build a description of the work and do not process elements until a terminal operation is invoked. Terminal operations such as forEach, count, collect, reduce, min⁡,max⁡\min, \max, sum and anyMatch trigger evaluation and produce a result or a side effect. Streams do not store data themselves and they do not modify the source collection. A stream can be consumed only once, so a new stream must be created for a second pass. Primitive specialisations such as IntStream avoid boxing and provide sum directly. To sum even numbers from one to ten, the program builds a list, calls stream, filters values divisible by two, converts to an IntStream with mapToInt and calls sum, producing thirty. To process Employee objects, the stream filters salaries above a threshold, maps each employee name to upper case and prints names with forEach. A good answer defines the pipeline structure, explains laziness and single use, distinguishes intermediate from terminal operations and writes both requested programs with their outputs. Mentioning that parallelStream can divide work across threads but is worthwhile only for large independent tasks adds practical balance. Noting that streams encourage immutable style and replace verbose loops with composable operations gives the design justification.

Result: filter is an intermediate operation and forEach is terminal; only employees with salary > 50000 are printed in uppercase.

min⁡,max⁡\min, \max
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Stream pipeline filter/map/terminal
  • Employee salary > 50000 filter
  • Output ASHA, MEENA
Q6a7MUnit 4 — ArrayList
Core Concept

Write a Java program using ArrayList to store 5 employee objects (ID, Name, Salary). Sort the list by salary in descending order using a Comparator.

Answer:

import java.util.*;
class Employee {
    int id; String name; double salary;
    Employee(int i, String n, double s) { id = i; name = n; salary = s; }
    public String toString() { return id + " " + name + " " + salary; }
}
public class SortEmp {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList&lt; >();
        list.add(new Employee(1, "Asha", 50000));
        list.add(new Employee(2, "Ravi", 72000));
        list.add(new Employee(3, "Meena", 60000));
        list.add(new Employee(4, "Kiran", 90000));
        list.add(new Employee(5, "Divya", 45000));
        list.sort(Comparator.comparingDouble(e -> e.salary).reversed());
        list.forEach(System.out::println);
    }
}

Output: 4 Kiran 90000.0 2 Ravi 72000.0 3 Meena 60000.0 1 Asha 50000.0 5 Divya 45000.0

Choosing between ArrayList and LinkedList. ArrayList and LinkedList both implement the List interface, but they use different internal structures and therefore have different performance profiles. ArrayList stores elements in a resizable array, so random access by index is constant time and iteration is fast because elements are contiguous in memory. Adding at the end is amortised constant time, but inserting or deleting in the middle requires shifting elements and takes linear time. When the array fills, it is replaced by a larger one and the elements are copied. LinkedList stores elements as doubly linked nodes, each holding a value and references to its neighbours. Insertion and deletion at the ends or at a known node are constant time, but reaching an element by index requires traversal from an end, so get is linear. Each node also carries two references, which increases memory use and hurts locality. LinkedList implements Deque as well as List, so it also supports queue and stack operations. ArrayList is the usual default for read heavy data and indexed access; LinkedList is useful when many insertions or deletions occur at the ends and indexed access is rare. A good answer compares storage, access time, insertion cost, memory use and typical use cases in a table, then gives a small example of adding and removing elements. Mentioning that both classes allow duplicates and preserve insertion order, and that neither is synchronised, completes the comparison. A note that ArrayDeque often beats LinkedList for queues shows awareness of modern library guidance.

Result: Comparator.comparingDouble(...).reversed() sorts by salary in descending order.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • ArrayList of 5 Employee objects
  • Comparator.comparingDouble(...).reversed()
  • Output descending: 90000,72000,60000,50000,45000
Q6b7MUnit 4 — HashMap Class
Core Concept

Write a Java program that uses a HashMap to store a Phone Book (Name as key, Phone Number as value). Implement a feature to search for a number by name.

Answer:

import java.util.*;
public class PhoneBook {
    public static void main(String[] args) {
        Map<String, String> book = new HashMap&lt; >();
        book.put("Asha", "9876543210");
        book.put("Ravi", "9123456780");
        String name = "Asha";
        if (book.containsKey(name))
            System.out.println(name + " -> " + book.get(name));
        else
            System.out.println("Not found");
    }
}

Output: Asha -> 9876543210

Key value storage with HashMap. HashMap implements the Map interface using a hash table. It stores entries as key value pairs and uses the hashCode of the key to choose a bucket, then equals to distinguish keys that land in the same bucket. Calling put with an existing key replaces its value, while get retrieves the value for a key and containsKey tests membership in constant average time. The implementation tolerates one null key and many null values, but it does not guarantee iteration order because bucket positions depend on hashes and on resizing. TreeMap provides sorted order and LinkedHashMap provides insertion or access order when order matters. Iteration can use keySet when only keys are needed, values when only values are needed, or entrySet when both are needed; entrySet is most efficient for key value pairs because it avoids a second lookup. A phone book is a natural example: the name is the key and the phone number is the value, so searching by name is a single get call. A marks example stores student names with integer marks and prints each entry. A good answer explains the hashing mechanism, writes a complete program that inserts entries and iterates with entrySet, shows the output and notes that order may vary. It should mention that a good hashCode distributes keys evenly and that mutable objects should not be used as keys because changing them can make the entry unreachable. Noting that HashMap is unsynchronised and that ConcurrentHashMap is preferred for shared concurrent access adds practical safety.

Result: HashMap stores name as key and number as value; containsKey/get provide O(1) average search by name.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Map<String,String> HashMap phone book
  • put to add, containsKey/get to search
  • Output Asha -> 9876543210
Q7a7MUnit 5 — Life Cycle Call backs
Core Concept

Explain the Spring Bean Lifecycle. Describe the steps from when a bean is instantiated until it is destroyed by the container.

Answer: Spring bean lifecycle:

  1. Instantiate the bean (constructor called).
  2. Populate properties / inject dependencies (@Autowired).
  3. Set BeanNameAware/BeanFactoryAware/ApplicationContextAware callbacks.
  4. BeanPostProcessor.preProcessBeforeInitialization.
  5. InitializingBean.afterPropertiesSet() or @PostConstruct custom init.
  6. BeanPostProcessor.postProcessAfterInitialization; bean is ready for use.
  7. On container shutdown: DisposableBean.destroy() or @PreDestroy.

How the Spring container manages beans. The Spring container is the inversion of control component that creates, configures and manages application objects called beans. BeanFactory provides the basic container services, while ApplicationContext adds enterprise features such as event publication, internationalisation, resource loading and integration with aspect oriented programming. The container reads configuration from XML files, Java configuration classes with at sign Bean methods, or annotations such as Component, Service, Repository and Controller discovered by component scanning. It then instantiates beans, resolves their dependencies and makes them available for use. The bean life cycle has a defined sequence. The container instantiates the bean, populates its properties and injects dependencies. Aware callbacks such as BeanNameAware, BeanFactoryAware and ApplicationContextAware let the bean learn about its environment. BeanPostProcessor objects may modify the bean before and after initialisation. Custom initialisation occurs through at sign PostConstruct or InitializingBean afterPropertiesSet, followed by post processing that can create proxies. The bean is then ready and is stored in the singleton cache by default. At shutdown, at sign PreDestroy or DisposableBean destroy performs cleanup. A good answer describes the container, names the main configuration styles and walks through the life cycle in order, explaining where dependency injection and custom init and destroy callbacks occur. Mentioning that scopes such as prototype, request and session change how long a bean lives, and that the container, not the bean, controls creation, is the inversion of control idea, makes the answer complete.

Result: The container controls creation, dependency injection, init callbacks and destruction, allowing resource setup/cleanup at precise points.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • Instantiation then dependency injection
  • @PostConstruct init and BeanPostProcessor hooks
  • @PreDestroy cleanup on shutdown
Q7b7MUnit 5 — BUILDING RESTFUL WEB SERVICES
Core Concept

Explain the architecture of a RESTful Web Service. How does Spring Boot handle a client request and return a JSON response?

Answer: A RESTful web service exposes resources identified by URLs and uses HTTP verbs (GET, POST, PUT, DELETE) with stateless requests, usually exchanging JSON.

  1. Client sends an HTTP request to the Spring Boot application.
  2. DispatcherServlet consults handler mappings and calls the matching @RestController method with @PathVariable/@RequestParam/@RequestBody data.
  3. The controller calls the service layer, gets domain objects, and returns them; HttpMessageConverter (Jackson) serialises them to JSON.
  4. Spring Boot auto-configures the embedded server, JSON converters and error handling.
@RestController
@RequestMapping("/students")
class StudentController {
    @GetMapping("/{id}")
    public Student get(@PathVariable int id) { return new Student(id, "Asha"); }
}

GET /students/7 -> JSON {"id":7,"name":"Asha"}.

Spring Boot and REST in practice. Spring Boot is an opinionated layer over Spring that removes most setup work. It provides starter dependencies that bundle compatible libraries, auto configuration that creates beans when certain classes are present, an embedded servlet container so an application runs as a standalone executable jar, and production features through Actuator. A RESTful web service exposes resources addressed by URLs and uses HTTP verbs with their standard meanings: GET reads, POST creates, PUT replaces, PATCH modifies and DELETE removes. Requests are stateless, and responses usually carry JSON with an appropriate status code. In Spring Boot, DispatcherServlet receives the request, consults handler mappings and invokes a method on a class annotated RestController. Path variables come from the URL with at sign PathVariable, query parameters with at sign RequestParam and request bodies with at sign RequestBody. The returned Java object is converted to JSON by an HttpMessageConverter backed by Jackson. A simple hello endpoint can accept a name parameter and return a greeting; a student endpoint can return a Student object for a given id. A good answer explains Boot benefits, maps HTTP verbs to operations, traces the request path through DispatcherServlet and converter, writes a small controller and states what the client receives. Mentioning that controllers should stay thin and delegate to a service layer, and that status codes such as 200, 201, 404 and 400 communicate the result, shows practical API design. Noting that REST is stateless and resource oriented ties the implementation back to the architectural style.

Result: Spring Boot's MVC stack maps the request, invokes the controller and returns a JSON response automatically.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the principle or language rule, write the code or structure with key terms defined, explain the execution or design decision and support the answer with a labelled diagram or comparison where useful.

Key Points

  • REST = URL resources + HTTP verbs + JSON
  • DispatcherServlet -> controller -> service
  • Jackson converts returned object to JSON