Top Banner Ad
BCS403 · 2023-2422 Questions

Object Oriented Programming with Java — 2023-24

Section A

2 Marks Each · 7 questions
Q1a2MUnit 1 — JVM
Survival ModePredicted

Describe JVM and byte code in Java Architecture.

The JVM is a virtual machine that executes Java bytecode. It loads class files, verifies them, allocates objects on the heap and runs instructions using an interpreter or just in time compiler. It also manages memory and garbage collection, so programs run on any operating system with a JVM.

Key Points

  • Executes platform neutral bytecode
  • Verifies classes and manages heap
  • Provides portability with garbage collection
Q1b2MUnit 1 — Object
Core Concept

Define the concept of classes and object in Java with a suitable example.

A class is a blueprint that defines fields and methods for a kind of object. An object is one concrete instance with its own values for those fields. Creating two objects from one class gives two independent states that respond to the same methods.

Key Points

  • Class is a blueprint
  • Object is an instance
  • Each object has independent state
Q1c2MUnit 1 — Interfaces
Core Concept

Explain Interfaces in Java with suitable example.

An interface is a contract listing methods a class must implement. A class uses implements and must provide bodies for the abstract methods. Interfaces support polymorphism because a reference of the interface type can point to any implementing object.

Key Points

  • Defines a method contract
  • Implemented by classes
  • Enables polymorphic references
Q1d2MUnit 2 — Use of try
Survival ModePredicted

Describe all the keywords used for exception handling in Java.

The five exception keywords are try, catch, finally, throw and throws. Try encloses risky code, catch handles a matching exception, finally performs cleanup, throw raises an exception object and declares possible exceptions in a method signature.

Key Points

  • Try catch and finally handle flow
  • Throw raises an object
  • Throws declares exceptions
Q1e2MUnit 2 — Thread Life Cycle
Core Concept

Describe various states achieved by the thread in its life cycle.

A thread begins in the new state, moves to runnable when started, then to running when scheduled. It may become blocked or waiting for a lock, input or a timed pause, and finally reaches terminated when run ends. Transitions are driven by start, scheduling, waits and completion.

Key Points

  • New and runnable states
  • Blocked or waiting states
  • Terminated after run ends
Q1f2MUnit 3 — ForEach Method
Core Concept

Write a Java program to create an ArrayList with five items and display all the elements using forEach method.

Answer:

import java.util.ArrayList;
public class Demo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java"); list.add("Python"); list.add("C++");
        list.add("Ruby"); list.add("Go");
        list.forEach(item -> System.out.println(item));
    }
}

Output: Java Python C++ Ruby Go Result: forEach(Consumer) from Iterable traverses the list and applies the lambda to every element in insertion order.

Key Points

  • ArrayList with five items
  • forEach takes a Consumer lambda
  • Prints all five elements in order
Q1g2MUnit 3 — Sealed Classes
Core Concept

Explain the concept of Sealed classes in Java with suitable example.

A sealed class restricts which classes may extend it by listing them after permits. Permitted subclasses must be final, sealed or non sealed. This closed hierarchy enables exhaustive pattern matching and prevents unknown subclasses from being added elsewhere in a program.

Key Points

  • Permits lists allowed subclasses
  • Subclasses must be final, sealed or non sealed
  • Enables exhaustive checks

Section B

7 Marks Each · 5 questions
Q2a7MUnit 1 — and Abstract Class
Core Concept

Explain abstraction and abstract classes in Java. Describe abstract method. With a suitable example demonstrate the application of abstract classes.

Answer: Abstraction hides implementation details and shows only essential behaviour. An abstract class cannot be instantiated; it may contain abstract methods (no body) that subclasses must implement, plus concrete methods and fields.

abstract class Shape {
    abstract double area();
    void display() { System.out.println("Area = " + area()); }
}
class Circle extends Shape {
    double r; Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}
public class Demo {
    public static void main(String[] args) {
        Shape s = new Circle(2);
        s.display();
    }
}

Output: Area = 12.566370614359172

Defining a contract with an abstract class. An abstract class is a class declared with the abstract keyword that cannot be instantiated directly. It may contain abstract methods, which have a declaration but no body, as well as concrete methods with implementations and fields with any access modifier. The purpose is to fix a common interface and reusable behaviour for a family of subclasses while leaving the parts that differ to those subclasses. For example, an abstract Shape class can declare area and implement display, while Circle and Rectangle supply their own area calculations. A subclass that extends an abstract class must implement every inherited abstract method unless it is itself declared abstract. Abstract classes support partial implementation, so they are useful when related classes share state or code, in contrast to interfaces which are best for pure capability contracts. In modern Java an interface may also have default and private methods, so the choice depends on whether a common state or is a relationship is needed. A reference of the abstract type can point to any concrete subclass object, and a call to an abstract method is resolved at run time by dynamic dispatch, which is a practical demonstration of polymorphism. A good answer defines the keyword and the restriction on instantiation, explains abstract and concrete members, states the obligation on subclasses, contrasts abstract classes with interfaces and gives a worked Shape example. Mentioning that abstract methods cannot be private, static or final because subclasses must override them shows attention to language rules.

Result: The abstract class fixes the interface (area) and reusable code (display) while leaving the specific computation to subclasses.

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

  • Abstract class cannot be instantiated
  • Abstract method has no body
  • Example Shape/Circle prints area
Q2b7MUnit 2 — Creating Threads
Core Concept

Describe the ways to create the threads in Java with suitable code. Also explain which method is more suitable to create threads.

Answer: Two ways to create a thread:

// 1) Extend Thread
class T1 extends Thread {
    public void run() { System.out.println("Thread by extends"); }
}
// 2) Implement Runnable
class T2 implements Runnable {
    public void run() { System.out.println("Thread by Runnable"); }
}
public class Demo {
    public static void main(String[] args) {
        new T1().start();
        new Thread(new T2()).start();
    }
}

Output (order may vary): Thread by extends / Thread by Runnable Which is better? Runnable is preferred: the task is separated from the thread, the class can still extend another class, and the same Runnable can be shared by several threads. Extending Thread is simpler when no other inheritance is needed.

Two ways to create a Java thread. A thread is a lightweight unit of execution inside a process, with its own program counter, stack and state while sharing the heap and other process resources with sibling threads. Java provides two classical ways to create one. The first is to extend the Thread class and override its run method. Creating an instance and calling start schedules the thread, and the JVM then calls run on the new thread of control. The second is to implement the Runnable interface, again defining run, and pass the runnable task to a Thread object before calling start. Implementing Runnable is generally preferred because Java allows only one superclass, so a class that implements Runnable remains free to extend another class; it also separates the task from the thread mechanism and lets the same Runnable object be shared by several threads. Calling run directly does not create a new thread, it simply invokes an ordinary method on the current thread, so start must be used. A good answer presents both approaches as complete code, explains what start does, compares the two approaches and states why Runnable is usually recommended. It should mention the thread priority and name methods only briefly, and note that modern code may use an ExecutorService instead of creating threads manually because a pool reuses threads and avoids the cost of repeated creation. Mentioning that thread output order is nondeterministic unless synchronisation is used shows understanding of concurrency.

Result: Always call start() (not run()) to obtain a new thread of execution.

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

  • extends Thread with run()
  • implements Runnable passed to Thread
  • Runnable preferred; start() launches thread
Q2c7MUnit 3 — Functional Interfaces
Survival ModePredicted

Explain the functional interfaces in Java. Describe lambda expressions with the help of functional interfaces.

Answer: A functional interface has exactly one abstract method, so a λ\lambda can supply its implementation. Examples: Runnable, Comparator, Predicate, Function, Consumer, Supplier.

import java.util.function.*;
public class FI {
    public static void main(String[] args) {
        Predicate<Integer> even = n -> n % 2 == 0;
        Function<Integer, Integer> twice = n -> n * 2;
        System.out.println(even.test(4));
        System.out.println(twice.apply(5));
    }
}

Output: true 10

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: Lambdas are concise implementations of the single abstract method of a functional interface; @FunctionalInterface makes the contract explicit.

λ\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

  • One abstract method enables lambda target
  • Predicate/Function examples
  • Output true and 10
Q2d7MUnit 4 — Hierarchy of Collection Framework
Survival ModePredictedRepeated

Describe Collections framework in Java with a suitable diagram displaying interfaces and classes and their hierarchy. Also explain the List, Set and Queue interfaces.

Answer: The Collection framework root interfaces are Iterable and Collection; Map is a parallel hierarchy.

List Set Map
Ordered sequence, duplicates allowed Unique elements, no duplicates Key-value pairs, unique keys
ArrayList, LinkedList HashSet, TreeSet HashMap, TreeMap
Access by index No index Access by key
get(0) contains(x) get(key)
List<String> l = new ArrayList&lt; >(); l.add("a"); l.add("a"); // size 2
Set<String> s = new HashSet&lt; >(); s.add("a"); s.add("a");    // size 1
Map<String,Integer> m = new HashMap&lt; >(); m.put("a", 1);      // key a -> 1

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: List preserves order/duplicates, Set enforces uniqueness, Map maps keys to values.

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.
Collections framework hierarchy Iterable Collection List Set Queue Map Map is a parallel hierarchy for key value pairs

Key Points

  • Hierarchy Iterable/Collection and Map
  • List ordered with duplicates
  • Set unique; Map key-value
Q2e7MUnit 5 — Spring Inversion of Control
Core Concept

Explain the difference between Dependency Injection (DI) and Inversion of Control (IoC) in Spring.

Answer:

IoC (Inversion of Control) DI (Dependency Injection)
General principle: control of object creation/lifecycle is handed to a framework Specific pattern: dependencies are supplied from outside
Container calls application code Container passes collaborators into objects
Achieved via DI, events, templates Types: constructor, setter, field injection
@Service class EmailService { void send(String m) { System.out.println(m); } }
@Component class UserService {
    private final EmailService email;
    UserService(EmailService e) { email = e; }  // DI inside IoC container
}

Principle and mechanism. Inversion of control and dependency injection are related but not identical. Inversion of control is the general design principle that control over object creation, configuration and lifecycle is transferred from application code to a framework or container. Instead of a class calling new for everything it needs and deciding when to initialise and clean up, it declares what it needs and the container manages the rest. This reversal is what makes frameworks extensible, because the framework calls application code through callbacks and configuration rather than application code driving every step. Dependency injection is one concrete way to achieve inversion of control. It means passing an object's collaborators into it from outside, usually by constructor, setter or field. In Spring, components are registered as beans, the container instantiates them and injects their declared dependencies, then manages their lifecycle. A service class that needs a mail sender receives an implementation through its constructor; it does not create one. Other techniques that implement inversion of control include event callbacks, template methods and aspect oriented advice, so injection is the common but not the only mechanism. A good answer defines both terms, gives the general versus specific relationship, lists the injection types, writes a small annotated example with a service and a collaborator and explains which object is in control before and after inversion. Mentioning that DI improves testability because mock implementations can be supplied in tests, and that IOC increases framework control while reducing direct coupling, gives the practical payoff. A closing sentence that Spring's container is an IOC container that uses DI as its main wiring mechanism ties the ideas together.

Result: IoC is the broad design principle implemented by Spring's container; DI is the concrete mechanism used to inject dependencies into beans.

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

  • IoC broad principle, DI specific pattern
  • Container controls lifecycle
  • Constructor injection example

Section C

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

Illustrate polymorphism and its types in Java. Differentiate between run-time and compile-time polymorphism. Write super class Shape with method displayArea() and sub class Rectangle. Demonstrate method overriding with this example.

Answer: Polymorphism = one interface, many implementations. Compile-time (static) polymorphism is method overloading; runtime (dynamic) polymorphism is method overriding via a superclass reference.

class Shape {
    void displayArea() { System.out.println("Shape area unknown"); }
}
class Rectangle extends Shape {
    int l = 4, b = 5;
    @Override void displayArea() { System.out.println("Rectangle area = " + (l*b)); }
    void displayArea(int x) { System.out.println("Square area = " + (x*x)); }
}
public class Demo {
    public static void main(String[] args) {
        Shape s = new Rectangle();
        s.displayArea();
        Rectangle r = new Rectangle();
        r.displayArea(3);
    }
}

Output: Rectangle area = 20 Square area = 9

One interface, many implementations. Polymorphism is the ability of the same name or reference to take different forms in different contexts. Compile time polymorphism is achieved by method overloading, where several methods share a name but differ in parameter list. The compiler chooses the correct method by matching the argument types and count, so the decision is made before the program runs. Runtime polymorphism is achieved by method overriding, where a subclass supplies its own implementation of a method declared in a superclass. A reference variable of the superclass type may hold an object of any subclass, and the Java Virtual Machine selects the implementation belonging to the actual object at run time; this is dynamic method dispatch. Using a superclass Shape with a displayArea method and a subclass Rectangle that overrides it, the statement Shape s = new Rectangle followed by s.displayArea prints the rectangle area, not the shape default. Adding an overloaded displayArea taking an integer demonstrates compile time selection on the same class. Rules for overriding require the same signature, a compatible return type, access that is not more restrictive and no narrowing of checked exceptions. Static, private and final methods cannot be overridden. A good answer defines both types, explains how the compiler or runtime chooses the method, writes and explains the Shape and Rectangle example and gives the overriding rules. Mentioning that polymorphism lets client code work with the abstraction and remain unchanged when new subclasses are added explains its design value.

Result: Runtime dispatch calls Rectangle's override; the overloaded version is chosen at compile time from the argument list.

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

  • Compile-time overloading vs runtime overriding
  • Shape superclass, Rectangle subclass
  • Output: area 20 and square area 9
Q3b7MUnit 1 — Constructors
Survival ModePredicted

Illustrate Constructors and their applications in Java. Describe the types of constructors used in Java. Write a class with name Student with attributes roll_number, name, branch and email. Write all argument constructor for class Student and create two objects with this constructor.

Answer: A constructor initialises a new object. Java supports a default (no-arg) constructor, a parameterised constructor and an implicit copy-like construction via assignment of references.

class Student {
    int roll_number; String name, branch, email;
    Student(int r, String n, String b, String e) {
        roll_number = r; name = n; branch = b; email = e;
    }
    void display() {
        System.out.println(roll_number + " " + name + " " + branch + " " + email);
    }
}
public class Demo {
    public static void main(String[] args) {
        Student s1 = new Student(101, "Asha", "CSE", "asha@uni.edu");
        Student s2 = new Student(102, "Ravi", "ECE", "ravi@uni.edu");
        s1.display(); s2.display();
    }
}

Output: 101 Asha CSE asha@uni.edu 102 Ravi ECE ravi@uni.edu

Why constructors matter. A constructor is a special member whose name is exactly the class name and which has no return type. It runs automatically when an object is created with the new operator, so it is the right place to establish valid initial state. If no constructor is declared, Java supplies a default no argument constructor, but declaring any constructor removes that automatic default. Constructors can be overloaded by giving them different parameter lists: one constructor may create an empty student record while another accepts a roll number and a name. When one constructor calls another in the same class it must use this as the first statement, and a subclass constructor must call a superclass constructor with super, either explicitly or through the implicit default call. The new operator allocates memory on the heap, initialises fields to default values, invokes the chosen constructor and finally returns a reference. Since fields can be made private, the constructor is often the only route by which invariant values enter an object. A good answer explains this sequence, distinguishes default and parameterised constructors, shows overloads and states that constructors are not inherited even though a subclass can invoke a superclass constructor. Mentioning that a constructor cannot be static, final or abstract and that it may throw exceptions completes the treatment. A copy constructor, which builds a new object from an existing one, is a common extension worth noting because it prevents accidental sharing of mutable fields.

Result: The all-argument constructor sets all four attributes at creation; each new call builds an independent Student object.

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

  • Default vs parameterised constructors
  • Student class with four attributes
  • Two objects created and printed
Q4a7MUnit 2 — Checked and Un-Checked Exceptions
Core Concept

Differentiate between checked and unchecked exceptions in Java. Write a Java program to demonstrate Arithmetic Exception handlings.

Answer:

Checked Unchecked
Compile-time checked; compiler forces handling Runtime exceptions, not checked by compiler
Extends Exception (e.g., IOException, SQLException) Extends RuntimeException (e.g., ArithmeticException, NullPointerException)
Must catch or declare with throws May be caught optionally
public class ArithmeticDemo {
    public static void main(String[] args) {
        try {
            int x = 10 / 0;
            System.out.println(x);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Done");
        }
    }
}

Output: Cannot divide by zero Done

Compile time checks and run time faults. Checked exceptions are abnormal conditions that a well written program is expected to anticipate, such as a missing file or a failed database connection. They extend Exception but not RuntimeException, and the compiler forces the programmer either to catch them or to declare them with throws. This makes failure handling explicit in the method signature. Unchecked exceptions extend RuntimeException and represent programming mistakes or impossible to recover states, such as dividing by zero, indexing past the end of an array or dereferencing null. The compiler does not require them to be caught, although catching them at a suitable boundary can still produce a friendly message. Errors such as OutOfMemoryError are separate from exceptions and normally should not be caught. ArithmeticException is an unchecked exception raised when an integer division has a zero divisor. A demonstration program places the division inside a try block, catches ArithmeticException, prints a clear message and uses finally to print a completion line. A good answer contrasts the two categories in a table, states their class hierarchy, explains the compiler rule and writes the demonstration with output. It should mention the exception hierarchy from Throwable down to Exception and Error, and note that catching a broad Exception should be done only when there is a genuine general recovery strategy. Mentioning that checked exceptions encourage callers to decide how to handle a predictable failure gives the design rationale.

Result: ArithmeticException is unchecked but can still be caught to handle division by zero gracefully.

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

  • Checked extends Exception; unchecked extends RuntimeException
  • Compiler enforces checked handling
  • ArithmeticException example prints two lines
Q4b7MUnit 2 — Input /Output Basics: Byte Streams and Character Streams
Survival Mode

Differentiate between with suitable examples: 1. Character streams and Byte Streams 2. wait() and notify()

Answer: 1. Character vs byte streams: Reader/Writer handle 16-bit Unicode text (FileReader, BufferedReader); InputStream/OutputStream handle 8-bit binary data (FileInputStream, BufferedInputStream). Example: FileReader reads characters from note.txt; FileInputStream copies an image. 2. wait() vs notify():

wait() notify()
Called on the lock object inside synchronized block Called on the same lock object
Releases lock and suspends current thread Wakes one waiting thread (notifyAll wakes all)
Must be in a loop to handle spurious wakeups Does not release the lock by itself
synchronized (lock) {
    while (empty) lock.wait();
    item = buffer.remove();
    lock.notify();
}

Text streams, binary streams and cooperation between threads. Java input and output are organised into byte streams and character streams. Byte streams descend from InputStream and OutputStream and move eight bit values, making them suitable for binary files such as images or compressed data; common classes are FileInputStream, FileOutputStream and their buffered wrappers. Character streams descend from Reader and Writer and handle sixteen bit Unicode characters, making them suitable for text files; FileReader, FileWriter, BufferedReader and BufferedWriter are the usual choices. Character streams apply the platform or specified charset encoding, so they avoid the mistakes that arise from treating text as raw bytes. The second part of the question concerns inter thread cooperation. The wait method is called on an object whose monitor is held inside a synchronized block or method. It releases the lock and suspends the calling thread until another thread calls notify or notifyAll on the same object. notify wakes one waiting thread, while notifyAll wakes all of them; the woken threads must reacquire the lock before continuing. Waiting is always placed inside a while loop that tests a condition, because spurious wakeups are permitted and another thread may change the condition first. A good answer compares the two stream families in a table, gives a read and write example, contrasts wait and notify and explains the synchronized and loop requirements. Mentioning that wait releases the lock while sleep does not is an important distinction.

Result: Character streams are for text and byte streams for binary; wait() suspends until notify() signals a state change.

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

  • Reader/Writer vs InputStream/OutputStream
  • wait releases lock; notify wakes a waiter
  • Always call wait in a loop inside synchronized
Q5a7MUnit 3 — Stream API
Predicted

Explain Java stream API and its applications. Describe Intermediate and terminal operations with suitable example. Write a program to print sum of all even numbers form an ArrayList containing all integers from 1 to 10.

Answer: A stream pipeline has intermediate operations (lazy, return a new stream: filter, map, sorted) and terminal operations (trigger evaluation and produce a result: forEach, count, sum, collect).

import java.util.*;
public class EvenSum {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList&lt; >();
        for (int i = 1; i &lt;= 10; i++) nums.add(i);
        int sum = nums.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum();
        System.out.println(sum);
    }
}

Output: 30 (2+4+6+8+10 = 30)

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/mapToInt are intermediate; sum is terminal and produces the single result 30.

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

  • Intermediate vs terminal operations
  • Stream over ArrayList 1..10
  • Sum of evens = 30
Q5b7MUnit 3 — Switch Expressions
Core Concept

Compare and contrast switch-case statement with switch-expression in Java. Explain with suitable example.

Answer:

switch statement switch expression (Java 14)
Control-flow statement, may fall through Expression that yields a value
break needed to stop fall-through No fall-through with arrow labels
Cannot be used in an assignment directly Can be assigned or returned
yield not available yield returns a value from a block
int day = 3;
String old = "";
switch (day) { case 1: old = "Mon"; break; default: old = "Other"; }
String now = switch (day) {
    case 1 -> "Mon";
    case 2 -> "Tue";
    default -> { yield "Other"; }
};
System.out.println(old + " " + now);

Output: Other Other

Statement and expression forms of switch. The traditional switch statement selects one of several blocks using a selector value of byte, short, int, char, String or an enum. Each case is labelled, and execution falls through to later cases until a break is encountered, which is a frequent source of bugs when a break is forgotten. A default label handles unmatched values. The switch expression, standardised in Java fourteen, treats selection as an expression that yields a value rather than a statement that performs a jump. It uses arrow labels, so there is no fall through, and it can be assigned directly to a variable or returned from a method. For a multi statement arm, the yield statement supplies the value. Both forms support multiple comma separated labels in one arm and pattern matching in newer releases. For day equal to three, a traditional switch may set a string variable through cases with breaks, while a switch expression simply returns the matching string with a default arm. A good answer compares the two forms in a table, explains fall through, break, default, arrow labels and yield, and writes equivalent examples with the same output. It should mention that the selector type restrictions are the same in the basic forms and that the expression form improves readability by making exhaustive value production explicit. Mentioning that compilers can check exhaustiveness when switching over enums or sealed types shows why the newer form supports better data modelling and fewer errors.

Result: Switch expressions are concise, value-producing and fall-through-safe; yield handles multi-statement arms.

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

  • Statement vs value-producing expression
  • Arrow labels avoid fall-through
  • yield returns block value
Q6a7MUnit 4 — LinkedList
Core Concept

Describe Linked List in Java collection framework. With suitable example describe any five methods available in Linked Lists.

Answer: LinkedList implements List and Deque using doubly linked nodes; it allows duplicates and supports stack/queue operations.

import java.util.*;
public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList<String> l = new LinkedList&lt; >();
        l.add("A"); l.add("B"); l.addFirst("Z"); l.addLast("C");
        System.out.println(l);
        System.out.println(l.getFirst());
        System.out.println(l.getLast());
        System.out.println(l.removeFirst());
        System.out.println(l.contains("B"));
        System.out.println(l.size());
    }
}

Output: [Z, A, B, C] Z C Z true 3

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: Five common methods: add, addFirst/addLast, getFirst/getLast, removeFirst, contains and size.

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

  • Doubly linked implementation of List/Deque
  • Methods addFirst/addLast/getFirst/removeFirst/contains
  • Output list [Z, A, B, C] then results
Q6b7MUnit 4 — LinkedList
Core Concept

Describe HashMap in Java collection framework. With suitable example describe any five methods available in HashMaps.

Answer: LinkedList implements List and Deque using doubly linked nodes; it allows duplicates and supports stack/queue operations.

import java.util.*;
public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList<String> l = new LinkedList&lt; >();
        l.add("A"); l.add("B"); l.addFirst("Z"); l.addLast("C");
        System.out.println(l);
        System.out.println(l.getFirst());
        System.out.println(l.getLast());
        System.out.println(l.removeFirst());
        System.out.println(l.contains("B"));
        System.out.println(l.size());
    }
}

Output: [Z, A, B, C] Z C Z true 3

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: Five common methods: add, addFirst/addLast, getFirst/getLast, removeFirst, contains and size.

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

  • Doubly linked implementation of List/Deque
  • Methods addFirst/addLast/getFirst/removeFirst/contains
  • Output list [Z, A, B, C] then results
Q7a7MUnit 5 — Life Cycle Call backs
Survival ModePredicted

Describe following: 1. Spring container 2. Spring bean life cycle

Answer:

  1. Spring container: the IoC container (BeanFactory/ApplicationContext) that creates, configures and manages beans. It reads XML, Java @Configuration or annotations and provides DI, AOP, event handling and lifecycle management.
  2. Bean lifecycle: instantiate -> inject dependencies -> Aware callbacks -> BeanPostProcessor before-init -> @PostConstruct/afterPropertiesSet -> BeanPostProcessor after-init -> ready for use -> @PreDestroy/DisposableBean destroy at shutdown.
@Configuration
class AppConfig { @Bean Student s() { return new Student(1, "Asha"); } }

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 owns bean creation and wiring; the lifecycle callbacks let beans initialise and release resources 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

  • Container = BeanFactory/ApplicationContext
  • Lifecycle steps from instantiation to destruction
  • @Bean / @Configuration example
Q7b7MUnit 5 — BUILDING RESTFUL WEB SERVICES
Survival Mode

Describe following: 3. Spring boot framework and its benefits 4. RESTFUL API with Spring boot

Answer: 3. Spring Boot is an opinionated framework built on Spring that auto-configures the application, provides embedded servers (Tomcat/Jetty), starter dependencies, actuator metrics and production-ready defaults. Benefits: minimal XML, fast setup, standalone executable JAR, easy microservices. 4. RESTful API with Spring Boot: annotate a class with @RestController, map URLs with @RequestMapping/@GetMapping/@PostMapping, bind data with @PathVariable/@RequestBody, return objects that Jackson converts to JSON.

@SpringBootApplication public class App { public static void main(String[] a) { SpringApplication.run(App.class, a); } }
@RestController class Hello {
    @GetMapping("/hello") public String hi(@RequestParam(defaultValue="world") String n) { return "Hello " + n; }
}

GET /hello?n=Java -> Hello Java

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 removes boilerplate configuration and makes REST endpoints quick to build and run.

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

  • Spring Boot auto-configuration and embedded server
  • REST via @RestController and mappings
  • Example GET /hello returns Hello Java