Java is platform independent because source code compiles to bytecode rather than native machine code. Each operating system has its own JVM that interprets or just in time compiles the same bytecode. Standard libraries hide system differences, so one class file runs unchanged across platforms.
Key Points
Bytecode is platform neutral
JVM adapts it locally
Standard APIs hide differences
Q1b2MUnit 1 — Constructors
Predicted
What is the role of a constructor in a Java class?
A constructor is a special method with the class name that initialises a new object. It has no return type and is called automatically with new. Java supplies a default constructor if none is written. Constructors may be overloaded with different parameter lists to create objects in different ways.
Key Points
Initialises new objects
Called automatically by new
Can be overloaded
Q1c2MUnit 2 — finally
Core Concept
What is the purpose of the finally block in Java exception handling?
The finally block holds cleanup code that runs after try and catch whether or not an exception occurred. It closes files, sockets and connections and runs even after a return or rethrow. It is skipped only if the JVM exits or the process is killed.
Key Points
Cleanup runs regardless
Used to close resources
Skipped only on JVM exit
Q1d2MUnit 2 — throw
Core Concept
How is throw different from throws?
Throw is used inside a method to raise a specific exception object and transfers control to the nearest matching catch. Throws appears in a method declaration and lists exception classes callers must handle or declare. One is an action; the other is a declaration.
Key Points
Throw raises an exception
Throws declares exceptions
Action versus signature
Q1e2MUnit 3 — Functional Interfaces
Survival ModePredicted
What is a functional interface? Give an example.
A functional interface has exactly one abstract method, so it can be the target of a lambda expression. It may include default and static methods and is often marked with at sign FunctionalInterface. The lambda supplies the body of the single abstract method.
Key Points
Exactly one abstract method
Target for lambda expressions
Optional FunctionalInterface annotation
Q1f2MUnit 4 — Stack
Survival ModePredicted
How does Stack differ from Queue?
Answer:
Stack
Queue
LIFO - last in, first out
FIFO - first in, first out
push(), pop(), peek()
offer(), poll(), peek()
java.util.Stack (legacy) / ArrayDeque
Queue interface, LinkedList/ArrayDeque
Used for expression evaluation, undo, DFS
Used for scheduling, BFS, buffers
Result: Stack removes the newest element; Queue removes the oldest element. Prefer ArrayDeque for both in new code.
Key Points
Stack LIFO vs Queue FIFO
push/pop vs offer/poll
Example uses: undo vs BFS
Q1g2MUnit 5 — GET
Survival ModePredicted
What is a GET vs POST request?
Answer:
GET
POST
Retrieves data; request body normally empty
Submits/creates data in the request body
Parameters in URL query string
Parameters in body (JSON/form)
Safe and idempotent
Neither safe nor idempotent
Cacheable, bookmarkable
Not normally cached
e.g., GET /students/7
e.g., POST /students with JSON body
Result: Use GET for reads and POST for creating/changing server state.
Key Points
GET reads, POST submits
GET query string vs POST body
GET safe/idempotent; POST not
Section B
7 Marks Each · 5 questions
Q2a7MUnit 1 — Data types
Core Concept
Discuss the different data types and control structures in Java with examples.
Answer:Primitive data types: byte(1), short(2), int(4), long(8), float(4), double(8), char(2), boolean(1 bit logical). Reference types include class, interface and array.
public class Demo {
public static void main(String[] args) {
int n = 5;
if (n > 3) System.out.println("big");
else System.out.println("small");
for (int i = 1; i <= 3; i++) System.out.print(i + " ");
while (n-- > 0) { }
}
}
Output: big followed by 1 2 3
Control structures: sequence, selection (if-else, switch), iteration (for, while, do-while), jump (break, continue, return).
Types and control flow in Java. Java is strongly typed, so every variable has a declared type known at compile time. The eight primitive types are byte, short, int, long, float, double, char and boolean. Integer types are signed and have fixed widths, floating point types follow binary floating point rules, char stores a Unicode code unit and boolean stores a logical value. Reference types include classes, interfaces, arrays and enums; a reference variable holds an address of an object rather than the object itself. Primitives are stored directly in stack frames or object fields, while objects live on the heap. Java also provides wrapper classes that let primitives be used where objects are required, with automatic boxing and unboxing. Control structures determine the order of execution. Sequence is the default. Selection uses if, if else and switch, with switch now available as an expression that returns a value. Iteration uses for, enhanced for, while and do while. Jump statements break, continue and return alter flow, and labelled break can exit an outer loop. Choosing the right loop matters: a for loop suits a known count, a while loop suits an unknown count and a do while loop guarantees at least one pass. A good answer lists the primitive and reference types, explains fixed sizes and wrappers, gives a small example using an if and a loop, and classifies the control structures. Mentioning that fixed type sizes make Java programs predictable across platforms and that compile time type checking catches many errors before execution gives the conceptual justification.
Result: Java's fixed-size primitives and structured control flow make programs predictable and portable.
For n≥1 elements the operation uses O(1) extra space.
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
Eight primitive types with fixed sizes
if-else/switch selection
for/while/do-while iteration with example output
Q2b7MUnit 2 — Multithreading: Thread
Predicted
Explain the concept of multithreading. Write a program to implement two threads printing numbers alternatively.
Answer: Multithreading lets a program run several threads concurrently within one process, sharing memory but having separate stacks.
public class Alternate {
static final Object lock = new Object();
static boolean turnA = true;
static class A extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
synchronized (lock) {
while (!turnA) { try { lock.wait(); } catch (InterruptedException e) {} }
System.out.println("A " + i);
turnA = false; lock.notifyAll();
}
}
}
}
static class B extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
synchronized (lock) {
while (turnA) { try { lock.wait(); } catch (InterruptedException e) {} }
System.out.println("B " + i);
turnA = true; lock.notifyAll();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new A(), t2 = new B();
t1.start(); t2.start(); t1.join(); t2.join();
}
}
Output: A 1 / B 1 / A 2 / B 2 / ... / A 5 / B 5
Concurrent execution inside one process. Multithreading means that a single program has several threads of execution advancing within one process. Each thread has its own program counter, stack and local variables, while all threads share the heap, the code and open resources. This makes communication easy but also creates races when two threads update the same data without coordination. Java started a thread by calling start on a Thread object; the JVM then invokes its run method on a new call stack. To make two threads print numbers alternately, the program must enforce turn taking with a shared lock and a condition flag. Each thread enters a synchronized block on the same lock object, checks the flag in a while loop, waits if it is not its turn, prints its number, flips the flag and calls notifyAll. The loop protects against spurious wakeups and ensures the condition is retested after reacquiring the monitor. The main thread can call join on both workers so the program does not finish before they do. A good answer defines multithreading, explains shared and private state, writes the two thread classes, explains synchronized, wait and notifyAll, and traces the alternation. It should distinguish start from run and note that the order of unrelated output is not guaranteed without synchronisation. Mentioning that excessive context switching can reduce performance and that modern applications often prefer thread pools keeps the discussion balanced.
Result: wait()/notifyAll() with a shared turn flag guarantees strict alternation.
For n≥1 elements the operation uses O(1) extra space.
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
Threads share process resources
wait/notifyAll with shared lock
Output alternates A and B 1..5
Q2c7MUnit 3 — Stream API
Survival ModePredicted
What is the Stream API in Java? How does it help in functional-style operations?
Answer: The Stream API (java.util.stream) processes collections with a functional pipeline: source -> zero or more intermediate operations (filter, map, sorted, distinct) -> one terminal operation (forEach, collect, count, reduce).
Streams are lazy: intermediate operations are not executed until a terminal operation starts.
They are not data storage and do not modify the source; a stream can be consumed only once.
Parallel streams can split work across threads with parallelStream().
List<Integer> l = Arrays.asList(1,2,3,4,5,6);
int sum = l.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum();
System.out.println(sum);
Output: 12
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, 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.
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
Source-intermediate-terminal pipeline
Lazy evaluation, no storage
Example even-number sum = 12
Q2d7MUnit 4 — ArrayList
Core Concept
Compare and contrast ArrayList and LinkedList in terms of performance and usage.
Answer:
ArrayList
LinkedList
Dynamic array, contiguous storage
Doubly linked nodes
Random access get(i) O(1)
Random access O(n)
add at end amortised O(1); middle O(n)
add/remove at ends O(1); middle needs traversal
More memory-efficient per element (except slack capacity)
Extra pointers per node
Best for frequent reads/indexing
Best for frequent insert/delete at ends, queues
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: Choose ArrayList for read-heavy indexed data; choose LinkedList when insertions/deletions dominate and index access is rare.
For n≥1 elements the operation uses O(1) extra space.
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 = array, fast get(i)
LinkedList = nodes, fast end insert/delete
Usage depends on read vs update pattern
Q2e7MUnit 5 — Bean Configuration styles Spring Boot: Spring Boot Build Systems
Core Concept
What is Spring Boot? How is it different from the traditional Spring framework?
Answer: Spring Boot is an opinionated extension of Spring that uses auto-configuration, starter POMs and embedded servers to build standalone, production-ready applications with minimal configuration.
Traditional Spring
Spring Boot
Extensive XML/Java configuration
Auto-configuration + defaults
External servlet container
Embedded Tomcat/Jetty
Manual dependency versions
Spring Boot starters/BOM
WAR deployed to server
Executable JAR with main()
@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Why Boot changed Spring development. Traditional Spring is a powerful framework but requires substantial explicit configuration. A developer chooses dependency versions, declares XML bean definitions or Java configuration classes, configures a DispatcherServlet, deploys a war file to an external servlet container and wires many infrastructure beans by hand. Spring Boot builds on that foundation with opinionated defaults. Starter dependencies group compatible libraries under one coordinate, auto configuration creates beans when certain classes are on the classpath, and an embedded Tomcat, Jetty or Undertow server lets the application run with a main method as an executable jar. Properties can be overridden through application properties, environment variables or command line arguments, so the same jar can run in different environments. Actuator adds health, metrics and other production endpoints. Traditional Spring gives maximum control when an application has unusual requirements, while Spring Boot optimises the common case and still allows any default to be replaced. It is not a replacement for Spring core; it is a faster way to build Spring applications. A good answer contrasts the two in a table covering configuration, server, packaging, dependency management and setup time, writes the standard at sign SpringBootApplication main class and states the benefits clearly. Mentioning that auto configuration is conditional, so it backs off when a user defines their own bean, shows how Boot keeps flexibility. Noting that Boot reduces boilerplate but does not remove the need to understand Spring concepts is a useful caveat.
Result: Spring Boot differs by removing boilerplate setup and delivering runnable applications with sensible defaults.
For n≥1 elements the operation uses O(1) extra space.
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
Auto-configuration and starters
Embedded server/executable JAR
@SpringBootApplication example
Section C
7 Marks Each · 10 questions
Q3a7MUnit 1 — Arrays & String
Core Concept
Write a Java program to take user input and display the reverse of a string.
Answer:
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String rev = new StringBuilder(s).reverse().toString();
System.out.println("Reverse: " + rev);
sc.close();
}
}
String r = "";
for (int i = s.length() - 1; i >= 0; i--) r += s.charAt(i);
Arrays and strings in Java. An array is a fixed length sequence of elements of one type, allocated with new and indexed from zero. Once created its length cannot change, although individual elements can be replaced. Multi dimensional arrays are arrays of arrays and need not be rectangular. A string is an object of the String class; it is immutable, so operations such as concatenation or reversal create new objects rather than changing the original. For repeated modification, StringBuilder or StringBuffer is efficient because it keeps a mutable character buffer. Reversing user input can be done by reading a line with Scanner, passing it to StringBuilder, calling reverse and converting back with toString. The manual equivalent copies characters from the last index down to zero into a new buffer, which shows why reversing is linear in the input length. A common examination question also asks for palindrome checking, where the reversed string is compared with the original after normalising case and punctuation. A good answer writes a complete program with imports, a class, a main method, input handling and output, then explains each step and the reason String is immutable. It should mention that Scanner should be closed, that array bounds are checked at run time and that StringBuilder is preferred inside loops. Mentioning the Unicode based indexing of char values and the availability of String methods such as charAt, length, substring and equals adds useful detail. A short trace with the input Java producing avaJ makes the behaviour concrete.
Result: String is immutable, so reversing builds a new String (StringBuilder is the efficient way).
For n≥1 elements the operation uses O(1) extra space.
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
Read with Scanner.nextLine()
StringBuilder.reverse() builds new string
Sample: Java -> avaJ
Q3b7MUnit 1 — JVM
Survival ModePredicted
Explain the concept of Java Virtual Machine and Java Runtime Environment.
Answer:
JVM: abstract machine that loads, verifies and executes bytecode; manages heap, stack, garbage collection and security. It is created when a Java program starts and dies when it exits.
JRE: the runtime package = JVM + core Java class libraries + supporting files, sufficient to run Java applications.
JDK: JRE + development tools (javac, javadoc, jar, debugger), needed to develop Java programs.
Relationship: JDK contains JRE, which contains JVM.
From source code to a running program. Java source is compiled by javac into class files containing bytecode, a stack based intermediate instruction set that is not tied to any particular processor or operating system. At run time the Java Virtual Machine loads the class, links and verifies it, then executes its bytecode. Loading is performed by a hierarchy of class loaders that delegate to their parents, which protects the core libraries and allows applications to define their own loading policies. Verification checks that bytecode obeys type and stack rules so that a malicious class cannot corrupt memory. The runtime data areas include a single heap shared by all threads, a method area for class metadata, a program counter and a Java stack for each thread, and native method stacks. Objects and arrays live on the heap; local variables and partial results live on stack frames. Execution may start in the interpreter and then hot methods are compiled to native code by the just in time compiler, giving high performance while preserving portability. Garbage collection reclaims heap objects that are no longer reachable, using algorithms such as mark and sweep, copying and generational collection. A good answer traces the pipeline from source to bytecode to JVM execution, names the main memory areas, explains verification and JIT compilation and describes automatic memory management. Mentioning that the JVM, not the language alone, provides portability and that each operating system needs its own JVM implementation makes the platform independence claim precise. Noting that class files can run anywhere the JVM conforms to the specification is the key conclusion.
Result: JVM executes, JRE provides the runtime environment, and JDK provides development tools.
For n≥1 elements the operation uses O(1) extra space.
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
JVM executes bytecode
JRE = JVM + libraries
JDK = JRE + tools
Q4a7MUnit 2 — Use of try
Survival ModePredicted
Write a Java program to handle multiple exceptions using try-catch-finally.
Answer:
public class MultiException {
public static void main(String[] args) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a / b);
} catch (NumberFormatException e) {
System.out.println("Number format error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Provide two numbers");
} catch (ArithmeticException e) {
System.out.println("Division by zero");
} catch (Exception e) {
System.out.println("Generic: " + e.getMessage());
} finally {
System.out.println("Finally always runs");
}
}
}
Sample: java MultiException 10 0 ->
Division by zero
Finally always runs
Handling errors without crashing the program. An exception is an object representing an abnormal event that interrupts normal instruction flow. Java uses try, catch and finally to handle such events. The try block encloses code that may fail, such as parsing arguments or dividing numbers. Each catch block declares the type of exception it can handle, and the runtime searches the catches in order, selecting the first compatible handler; subclass handlers must therefore appear before superclass handlers. When a handler runs, the program can print a message, substitute a safe value or rethrow the exception. The finally block is executed whether or not an exception occurred, which makes it the right place to close files, sockets and database connections. It runs even when a catch returns or rethrows, and it is skipped only if the JVM exits or the process is killed. Multiple catches allow different responses to NumberFormatException, ArrayIndexOutOfBoundsException and ArithmeticException in the same program. Try with resources is a newer form that closes resources automatically and often removes the need for an explicit finally. A good answer writes a complete program with several specific catches and a general Exception catch, shows a sample run such as dividing ten by zero, and explains the order of execution. It should define checked and unchecked exceptions briefly and state that the finally block runs after the try or selected catch, even when no exception happened. Mentioning that exception handling separates normal logic from error recovery is the design principle to emphasise.
Result: Multiple catches handle specific exceptions, a general catch is last, and finally executes regardless.
For n≥1 elements the operation uses O(1) extra space.
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
Multiple specific catch blocks
Subclass catch before superclass
finally always executes; sample division by zero
Q4b7MUnit 2 — Creating Threads
Core Concept
Write a Java program that creates two threads – one to print even numbers and the other for odd numbers.
Answer:
public class EvenOdd {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
Thread even = new Thread(() -> {
for (int i = 2; i <= 10; i += 2) {
synchronized (lock) { System.out.println("Even: " + i); }
}
});
Thread odd = new Thread(() -> {
for (int i = 1; i <= 9; i += 2) {
synchronized (lock) { System.out.println("Odd: " + i); }
}
});
even.start(); odd.start(); even.join(); odd.join();
}
}
Output (the two series may interleave):
Even: 2
Odd: 1
Even: 4
Odd: 3
Even: 6
Odd: 5
Even: 8
Odd: 7
Even: 10
Odd: 9
Concurrent execution inside one process. Multithreading means that a single program has several threads of execution advancing within one process. Each thread has its own program counter, stack and local variables, while all threads share the heap, the code and open resources. This makes communication easy but also creates races when two threads update the same data without coordination. Java started a thread by calling start on a Thread object; the JVM then invokes its run method on a new call stack. To make two threads print numbers alternately, the program must enforce turn taking with a shared lock and a condition flag. Each thread enters a synchronized block on the same lock object, checks the flag in a while loop, waits if it is not its turn, prints its number, flips the flag and calls notifyAll. The loop protects against spurious wakeups and ensures the condition is retested after reacquiring the monitor. The main thread can call join on both workers so the program does not finish before they do. A good answer defines multithreading, explains shared and private state, writes the two thread classes, explains synchronized, wait and notifyAll, and traces the alternation. It should distinguish start from run and note that the order of unrelated output is not guaranteed without synchronisation. Mentioning that excessive context switching can reduce performance and that modern applications often prefer thread pools keeps the discussion balanced.
Result: One thread prints 2..10 and the other prints 1..9; start() launches them concurrently and join() waits for both.
For n≥1 elements the operation uses O(1) extra space.
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.
What are functional interfaces and how are they implemented using lambda expressions?
Answer: A functional interface has exactly one abstract method; a λ is an anonymous implementation of that method with syntax (parameters) -> expression or block.
@FunctionalInterface
interface Operation { int apply(int a, int b); }
public class Demo {
public static void main(String[] args) {
Operation max = (a, b) -> a > b ? a : b;
System.out.println(max.apply(7, 12));
}
}
Output: 12
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 λ 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 λ has no name and no separate class declaration, it removes a large amount of boilerplate while keeping static type checking. Aλ 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 λ 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 λ implements Operation.apply at runtime; the compiler checks that only one abstract method exists.
λAλ
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
Functional interface = one abstract method
Lambda syntax (params)->body
Example prints 12
Q5b7MUnit 3 — Type Annotations
Core Concept
Describe the role of annotations in Java and how type annotations are used.
Answer: Annotations are metadata (introduced Java 5) applied with @Name to classes, methods, fields and parameters; they can be read by compilers or at runtime via reflection. Examples: @Override, @Deprecated, @SuppressWarnings, @FunctionalInterface.
Type annotations (Java 8) extend annotations to type usages with TYPEUSE target, so they can annotate array elements, generic arguments, casts and throws clauses:
Metadata that tools can read. An annotation is metadata written with an at sign before a name and attached to a declaration such as a class, method, field, parameter or package. Annotations do not change program logic by themselves, but compilers, frameworks and reflection code can read them to check errors, generate code or configure behaviour. Built in examples include Override, which asks the compiler to verify an override, Deprecated, which warns that a member should no longer be used, SuppressWarnings, which suppresses selected compiler warnings, and FunctionalInterface, which checks the single abstract method rule. Annotation definitions specify targets, using ElementType, and retention, using RetentionPolicy. Source retention annotations are discarded after compilation, class retention annotations are stored in the class file but not normally visible at run time, and runtime retention annotations can be inspected through reflection, which is how frameworks such as Spring discover components. Type annotations introduced in Java eight extend the use of annotations to type contexts through the TYPE USE target. They can annotate array elements, generic type arguments, casts, method receiver types and throws clauses, for example a nonnull string or a list of notnull strings. This permits static analysis tools to check nullness or units at each type occurrence rather than only at a declaration. A good answer defines annotations, names common examples, explains target and retention, describes type annotations and gives examples. Mentioning that annotations are not executed and need a consumer such as a compiler plugin or framework makes their role clear.
Result: Annotations document or drive tooling; type annotations allow finer checks such as nullness on any type occurrence, not only declarations.
TYPEUSE
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
Annotations = metadata with @ syntax
Examples @Override, @Deprecated
Type annotations apply to type uses via TYPE_USE
Q6a7MUnit 4 — HashMap Class
Survival ModePredicted
Write a program to demonstrate the use of HashMap and iterate through keys and values.
Answer:
import java.util.*;
public class MapIterate {
public static void main(String[] args) {
Map<String, Integer> marks = new HashMap< >();
marks.put("Asha", 88); marks.put("Ravi", 74); marks.put("Meena", 91);
for (Map.Entry<String, Integer> e : marks.entrySet())
System.out.println(e.getKey() + " = " + e.getValue());
}
}
Output (order may vary):
Asha = 88
Ravi = 74
Meena = 91
Alternative: iterate keys with keySet() or values with values().
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: entrySet() gives key-value pairs for iteration; HashMap ordering is unspecified, so use TreeMap/LinkedHashMap for deterministic order.
For n≥1 elements the operation uses O(1) extra space.
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
HashMap stores key-value pairs
entrySet() iteration
Order unspecified for HashMap
Q6b7MUnit 4 — Hierarchy of Collection Framework
Survival ModePredictedRepeated
Discuss the hierarchy of the Collection framework in Java. Differentiate between List, Set, and Map.
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< >(); l.add("a"); l.add("a"); // size 2
Set<String> s = new HashSet< >(); s.add("a"); s.add("a"); // size 1
Map<String,Integer> m = new HashMap< >(); 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≥1 elements the operation uses O(1) extra space.
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
Hierarchy Iterable/Collection and Map
List ordered with duplicates
Set unique; Map key-value
Q7a7MUnit 5 — Spring Core Basics-Spring Dependency Injection concepts
Predicted
Explain the concept of Dependency Injection and its types in Spring. Develop a simple API in Spring Boot to perform CRUD operations using a list as storage.
Answer: Dependency Injection types:
Constructor injection: dependencies passed via constructor (recommended, immutable).
Setter injection: provided through setter methods.
Field injection: @Autowired directly on fields (least recommended).
CRUD API using a list as storage:
@RestController
@RequestMapping("/items")
public class ItemController {
private final List<String> items = new CopyOnWriteArrayList< >(List.of("A", "B"));
@GetMapping public List<String> all() { return items; }
@GetMapping("/{i}") public String get(@PathVariable int i) { return items.get(i); }
@PostMapping public void add(@RequestBody String s) { items.add(s); }
@PutMapping("/{i}") public void update(@PathVariable int i, @RequestBody String s) { items.set(i, s); }
@DeleteMapping("/{i}") public void delete(@PathVariable int i) { items.remove(i); }
}
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 types differ in how dependencies are supplied; the controller above implements GET/POST/PUT/DELETE with an in-memory list.
For n≥1 elements the operation uses O(1) extra space.
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
Constructor/setter/field DI
RestController with CRUD mappings
In-memory CopyOnWriteArrayList storage
Q7b7MUnit 5 — Spring Boot Code Structure
Core Concept
Describe the structure of a basic Spring Boot application. What are the advantages of using Spring Boot over traditional web frameworks?
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }
}
Advantages: no XML, auto-configuration, embedded server, starter dependencies, actuator, easy testing and standalone JAR deployment.
A conventional Spring Boot project. A basic Spring Boot application follows a package layout that makes component scanning predictable. Under src main java, a root package such as com example demo contains the main application class annotated with at sign SpringBootApplication. Subpackages hold controllers, services, repositories and model or domain classes. Placing the main class at the root of those subpackages matters because component scanning searches downward from its package. Under src main resources, application properties or application yaml holds configuration such as the server port, datasource settings and logging levels; static assets and templates also live there if the application serves pages. Under src test java, tests use Spring Boot Test support and can start a slice of the application context. The build file, either pom xml or build gradle, declares the parent or plugin and starter dependencies such as web, data jpa and test. The main method calls SpringApplication run, which starts the embedded server, creates the application context and performs auto configuration. Advantages over traditional web frameworks include no XML boilerplate, embedded server, starter dependencies, production ready Actuator endpoints, easy testing with slices and a standalone jar that simplifies deployment. A good answer describes the directory structure with a small tree, explains the role of each layer, shows the main class and lists the advantages with reasons. Mentioning that the layered structure keeps HTTP concerns in controllers, business rules in services and persistence in repositories shows how the layout supports maintainability. A note that configuration can be externalised per profile explains why the same code moves between development and production.
Result: A conventional package layout plus starters lets a Spring Boot application be developed and launched with minimal setup.
For n≥1 elements the operation uses O(1) extra space.
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.