0% found this document useful (0 votes)
4 views39 pages

Java Answers 20marks

The document is a comprehensive answer bank for a Java internal exam covering topics such as multi-threading, deadlock, synchronization, inter-thread communication, exception handling, and generics. It includes detailed explanations, Java programs, and key points for each topic, providing a structured overview of essential Java concepts. Each section is assigned marks, indicating its importance in the exam context.

Uploaded by

maharishi6002
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

Java Answers 20marks

The document is a comprehensive answer bank for a Java internal exam covering topics such as multi-threading, deadlock, synchronization, inter-thread communication, exception handling, and generics. It includes detailed explanations, Java programs, and key points for each topic, providing a structured overview of essential Java concepts. Each section is assigned marks, indicating its importance in the exam context.

Uploaded by

maharishi6002
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Internal Exam

Comprehensive Answer Bank


20 Marks per Question | Detailed Explanations & Programs

Java Internal Exam Answer Bank | Page 1 of 39


PART 1: Multi-threading & Concurrency
Q1. Thread Life Cycle & States
[20 Marks]

Introduction
A thread in Java is a lightweight sub-process. The Java Thread model defines six states through which
a thread transitions during its lifetime. The [Link] enum captures these states.

1. Thread States Explained (5 Marks)


a) NEW
A thread is in the NEW state after it is created using new Thread() but before start() is called. The OS
has not yet allocated resources.
b) RUNNABLE
After start() is called, the thread enters RUNNABLE state. It is eligible to run and the JVM thread
scheduler decides when to actually execute it.
c) BLOCKED
A thread is BLOCKED when it is waiting to acquire a monitor lock held by another thread (e.g., trying to
enter a synchronized block/method).
d) WAITING
A thread enters WAITING state by calling wait(), join() (without timeout), or [Link](). It waits
indefinitely until another thread performs a specific action.
e) TIMED_WAITING
Similar to WAITING but with a specified timeout: sleep(ms), wait(ms), join(ms), or
[Link]().
f) TERMINATED
The thread has completed execution (run() method returned) or terminated due to an uncaught
exception.

2. State Transition Diagram (3 Marks)


NEW → (start()) → RUNNABLE → (scheduler) → RUNNING
RUNNING → (sleep/wait/join) → TIMED_WAITING / WAITING → (notify/interrupt/timeout) →
RUNNABLE
RUNNING → (synchronized block unavailable) → BLOCKED → (lock acquired) → RUNNABLE
RUNNING → (run() ends) → TERMINATED

3. Java Program (10 Marks)


public class ThreadStatesDemo {
static Object lock = new Object();

public static void main(String[] args) throws InterruptedException {


Thread t1 = new Thread(() -> {
[Link]('T1 Running');

Java Internal Exam Answer Bank | Page 2 of 39


synchronized(lock) {
try { [Link](2000); } catch(InterruptedException e) {}
}
}, 'T1');

Thread t2 = new Thread(() -> {


synchronized(lock) {
try { [Link](3000); } catch(InterruptedException e) {}
}
}, 'T2');

[Link]('T1 state after new: ' + [Link]()); // NEW


[Link]();
[Link]('T1 state after start: ' + [Link]()); // RUNNABLE
[Link](200);
[Link]('T1 state after wait: ' + [Link]()); // TIMED_WAITING
[Link]();
[Link](200);
[Link]('T2 state (sleep): ' + [Link]()); // TIMED_WAITING
[Link](); [Link]();
[Link]('T1 state at end: ' + [Link]()); // TERMINATED
}
}

2 Marks: Key Points


• getState() returns the current state of the thread as [Link] enum.
• A thread can only be started once; calling start() again throws IllegalThreadStateException.

Java Internal Exam Answer Bank | Page 3 of 39


Q2. Deadlock in Java
[20 Marks]

Introduction
A deadlock occurs when two or more threads are permanently blocked, each waiting for a resource
held by the other. Java does not automatically detect or recover from deadlocks.

1. Conditions for Deadlock (4 Marks)


Four conditions (Coffman's) must hold simultaneously:
1. Mutual Exclusion – Resources cannot be shared.
2. Hold and Wait – A thread holds a resource and waits for another.
3. No Preemption – Resources cannot be forcibly taken.
4. Circular Wait – A circular chain of threads waiting for each other.

2. Java Program Demonstrating Deadlock (10 Marks)


public class DeadlockDemo {
static final Object LOCK_A = new Object();
static final Object LOCK_B = new Object();

public static void main(String[] args) {


Thread t1 = new Thread(() -> {
synchronized(LOCK_A) {
[Link]('T1: Holding LOCK_A, waiting for LOCK_B...');
try { [Link](100); } catch(InterruptedException e) {}
synchronized(LOCK_B) {
[Link]('T1: Acquired LOCK_B');
}
}
});

Thread t2 = new Thread(() -> {


synchronized(LOCK_B) {
[Link]('T2: Holding LOCK_B, waiting for LOCK_A...');
try { [Link](100); } catch(InterruptedException e) {}
synchronized(LOCK_A) {
[Link]('T2: Acquired LOCK_A');
}
}
});

[Link]();
[Link]();
[Link]('Main: Both threads started (deadlock will occur)');
}
}

3. Deadlock Prevention (4 Marks)


1. Lock Ordering: Always acquire locks in a fixed global order.

Java Internal Exam Answer Bank | Page 4 of 39


2. Lock Timeout: Use tryLock() with timeout from [Link].
3. Avoid Nested Locks: Minimize acquiring multiple locks simultaneously.
4. Use Higher-Level Concurrency: Prefer [Link] utilities.

2 Marks: Detection
Java's ThreadMXBean can detect deadlocks programmatically via findDeadlockedThreads(). The
jstack tool also shows deadlock reports.

Java Internal Exam Answer Bank | Page 5 of 39


Q3. Synchronization in Java
[20 Marks]

Introduction (2 Marks)
Synchronization is the mechanism that ensures only one thread at a time can access a shared
resource (critical section). Without it, race conditions cause inconsistent results.

1. The synchronized Keyword (4 Marks)


a) Synchronized Method:
When a thread invokes a synchronized method, it acquires the intrinsic lock (monitor) of the object.
Other threads trying to call any synchronized method on the same object are blocked.
b) Synchronized Block:
More granular control. Only the specified object's lock is acquired, reducing contention compared to a
full method lock.

2. Java Program (10 Marks)


class Counter {
private int count = 0;

// Synchronized method
public synchronized void increment() {
count++;
}

// Synchronized block
public void incrementBlock() {
synchronized(this) {
count++;
}
}

public int getCount() { return count; }


}

public class SyncDemo {


public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(() -> {
for(int i = 0; i < 1000; i++) [Link]();
});
Thread t2 = new Thread(() -> {
for(int i = 0; i < 1000; i++) [Link]();
});
[Link](); [Link]();
[Link](); [Link]();
[Link]('Final count: ' + [Link]()); // Always 2000
}
}

Java Internal Exam Answer Bank | Page 6 of 39


3. Types of Locks (2 Marks)
• Intrinsic Locks (Monitor Locks): Built-in with synchronized keyword.
• Explicit Locks: [Link] – more flexible.

4. Volatile vs Synchronized (2 Marks)


volatile guarantees visibility but not atomicity. synchronized guarantees both. Use synchronized for
compound actions (read-modify-write).

Java Internal Exam Answer Bank | Page 7 of 39


Q4. Inter-Thread Communication: Producer-Consumer
[20 Marks]

Introduction (2 Marks)
The Producer-Consumer problem demonstrates inter-thread communication where one thread
produces data and another consumes it from a shared buffer. Java's wait(), notify(), and notifyAll()
facilitate this coordination.

1. Key Methods (3 Marks)


• wait(): Causes the current thread to release the lock and wait until another thread calls notify().
• notify(): Wakes up one thread waiting on the object's monitor.
• notifyAll(): Wakes up all threads waiting on the object's monitor.
Note: These must be called from a synchronized context.

2. Java Program (13 Marks)


import [Link];
import [Link];

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

public synchronized void produce(int item) throws InterruptedException {


while([Link]() == CAPACITY) {
[Link]('Buffer full. Producer waiting...');
wait();
}
[Link](item);
[Link]('Produced: ' + item + ' | Buffer: ' + queue);
notify();
}

public synchronized void consume() throws InterruptedException {


while([Link]()) {
[Link]('Buffer empty. Consumer waiting...');
wait();
}
int item = [Link]();
[Link]('Consumed: ' + item + ' | Buffer: ' + queue);
notify();
}
}

public class ProducerConsumer {


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

Thread producer = new Thread(() -> {


for(int i = 1; i <= 10; i++) {

Java Internal Exam Answer Bank | Page 8 of 39


try { [Link](i); [Link](100); }
catch(InterruptedException e) { [Link]().interrupt(); }
}
});

Thread consumer = new Thread(() -> {


for(int i = 0; i < 10; i++) {
try { [Link](); [Link](300); }
catch(InterruptedException e) { [Link]().interrupt(); }
}
});

[Link]();
[Link]();
}
}

2 Marks: Why while instead of if?


We use while for waiting to guard against spurious wakeups. If the condition is still not met after
wakeup, the thread must wait again.

Java Internal Exam Answer Bank | Page 9 of 39


Q5. Fork/Join Framework
[20 Marks]

Introduction (3 Marks)
The Fork/Join Framework (introduced in Java 7) is designed for parallel computation. It follows the
divide-and-conquer paradigm: a large task is recursively split (forked) into smaller subtasks, executed
in parallel, and results are joined back.

1. Key Classes (3 Marks)


• ForkJoinPool: The thread pool that manages worker threads. Uses work-stealing algorithm.
• RecursiveTask<V>: Extends ForkJoinTask for tasks that return a result.
• RecursiveAction: Extends ForkJoinTask for tasks that return no result.

2. Java Program: Parallel Sum (10 Marks)


import [Link].*;

class SumTask extends RecursiveTask<Long> {


private static final int THRESHOLD = 1000;
private long[] array;
private int start, end;

SumTask(long[] array, int start, int end) {


[Link] = array; [Link] = start; [Link] = end;
}

@Override
protected Long compute() {
if((end - start) <= THRESHOLD) {
long sum = 0;
for(int i = start; i < end; i++) sum += array[i];
return sum;
}
int mid = (start + end) / 2;
SumTask left = new SumTask(array, start, mid);
SumTask right = new SumTask(array, mid, end);
[Link](); // Async execute left
long rightResult = [Link](); // Execute right in current thread
long leftResult = [Link](); // Wait for left
return leftResult + rightResult;
}
}

public class ForkJoinDemo {


public static void main(String[] args) {
long[] data = new long[10000];
for(int i = 0; i < [Link]; i++) data[i] = i + 1;

ForkJoinPool pool = new ForkJoinPool();


SumTask task = new SumTask(data, 0, [Link]);
long result = [Link](task);

Java Internal Exam Answer Bank | Page 10 of 39


[Link]('Sum: ' + result); // 50005000
}
}

4 Marks: Work Stealing


The ForkJoinPool uses a work-stealing algorithm: idle threads steal tasks from busy threads' deques.
This maximizes CPU utilization.

Java Internal Exam Answer Bank | Page 11 of 39


PART 2: Exception Handling & Generics
Q6. Exception Handling Mechanism
[20 Marks]

Introduction (2 Marks)
Exception Handling in Java is a mechanism to handle runtime errors gracefully, maintaining normal
program flow. Java uses try-catch-finally blocks and a hierarchy of Throwable classes.

1. Exception Hierarchy (3 Marks)


Throwable → Error (JVM errors, not usually handled) and Exception.
Exception → Checked Exceptions (must be declared/handled) and RuntimeException (unchecked).
Examples: IOException (checked), NullPointerException, ArrayIndexOutOfBoundsException
(unchecked).

2. try-catch-finally (3 Marks)
• try: Contains the risky code.
• catch: Handles a specific exception type.
• finally: Always executes (for cleanup: closing files, DB connections).

3. Java Program (10 Marks)


import [Link];

public class ExceptionDemo {


public static int divide(int a, int b) {
return a / b; // ArithmeticException if b==0
}

public static void main(String[] args) {


int[] arr = {10, 20, 30};

try {
// Arithmetic exception
int result = divide(10, 0);
[Link]('Result: ' + result);
} catch(ArithmeticException e) {
[Link]('Caught ArithmeticException: ' + [Link]());
}

try {
// Array index exception
[Link](arr[10]);
} catch(ArrayIndexOutOfBoundsException e) {
[Link]('Caught: ' + [Link]());
} finally {
[Link]('Finally block: always runs');
}

Java Internal Exam Answer Bank | Page 12 of 39


try {
// Null pointer
String s = null;
[Link]();
} catch(NullPointerException e) {
[Link]('NullPointerException caught');
} catch(Exception e) {
[Link]('Generic exception: ' + [Link]());
}

// Try-with-resources (Java 7+)


try([Link] sr = new [Link]('test')) {
[Link]('Read: ' + (char) [Link]());
} catch([Link] e) {
[Link]('IOException: ' + [Link]());
}
}
}

2 Marks: Best Practices


• Catch specific exceptions before generic ones.
• Use finally or try-with-resources for cleanup.
• Never swallow exceptions silently (empty catch block).

Java Internal Exam Answer Bank | Page 13 of 39


Q7. User-Defined (Custom) Exceptions
[20 Marks]

Introduction (2 Marks)
Custom exceptions allow programmers to create application-specific error types. They extend
Exception (for checked) or RuntimeException (for unchecked) and can carry additional context.

1. Why Custom Exceptions? (2 Marks)


• Represent domain-specific errors meaningfully (e.g., InvalidAgeException,
InsufficientFundsException).
• Allow caller to handle them distinctly.
• Carry extra data (error codes, messages).

2. Steps to Create a Custom Exception (2 Marks)


1. Create a class extending Exception or RuntimeException.
2. Add constructors (default, message, cause).
3. Throw using throw new CustomException(...).
4. Declare in method signature using throws if checked.

3. Java Program: InvalidAgeException (12 Marks)


// Custom Checked Exception
class InvalidAgeException extends Exception {
private int age;

public InvalidAgeException(String message, int age) {


super(message);
[Link] = age;
}

public int getAge() { return age; }

@Override
public String toString() {
return 'InvalidAgeException: ' + getMessage() + ' (Age provided: ' + age +
')';
}
}

// Custom Unchecked Exception


class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(double amount) {
super('Insufficient funds. Required: ' + amount);
}
}

public class CustomExceptionDemo {


static void validateAge(int age) throws InvalidAgeException {
if(age < 18) {

Java Internal Exam Answer Bank | Page 14 of 39


throw new InvalidAgeException('Age must be 18 or above for registration',
age);
}
[Link]('Age ' + age + ' is valid. Registration successful.');
}

static void withdraw(double balance, double amount) {


if(amount > balance) throw new InsufficientFundsException(amount - balance);
[Link]('Withdrawn: ' + amount + '. Balance: ' + (balance -
amount));
}

public static void main(String[] args) {


// Test InvalidAgeException
int[] ages = {25, 15, 18};
for(int age : ages) {
try {
validateAge(age);
} catch(InvalidAgeException e) {
[Link]('Caught: ' + e);
}
}

// Test InsufficientFundsException
try {
withdraw(500.0, 700.0);
} catch(InsufficientFundsException e) {
[Link]('Caught: ' + [Link]());
}
}
}

2 Marks: Checked vs Unchecked Custom Exceptions


Extend Exception for errors that callers should handle (checked). Extend RuntimeException for
programming errors or situations where recovery is not expected (unchecked).

Java Internal Exam Answer Bank | Page 15 of 39


Q8. Generic Classes and Methods
[20 Marks]

Introduction (2 Marks)
Generics enable type-independent code that works with any object type while maintaining type safety at
compile time. They eliminate the need for casting and catch type errors early.

1. Benefits of Generics (2 Marks)


• Type Safety: Compiler checks type compatibility.
• Code Reusability: One class/method serves multiple types.
• No Casting: Return types are automatically inferred.
• Readability: Code intent is clearer.

2. Bounded Type Parameters (2 Marks)


• <T extends Number>: T must be Number or its subclass.
• <T super Integer>: T must be Integer or its superclass.
• Wildcards: <?> (unknown), <? extends T>, <? super T>.

3. Java Program (12 Marks)


import [Link];
import [Link];

// Generic Class
class Box<T> {
private T value;

public Box(T value) { [Link] = value; }


public T getValue() { return value; }
public void setValue(T value) { [Link] = value; }

@Override
public String toString() { return 'Box[' + value + ']'; }
}

// Generic Pair Class


class Pair<K, V> {
private K key; private V value;
public Pair(K key, V value) { [Link] = key; [Link] = value; }
public K getKey() { return key; }
public V getValue() { return value; }
public String toString() { return '(' + key + ', ' + value + ')'; }
}

// Generic Methods
class GenericUtils {
// Generic method to find max in array
public static <T extends Comparable<T>> T findMax(T[] arr) {
T max = arr[0];

Java Internal Exam Answer Bank | Page 16 of 39


for(T t : arr) if([Link](max) > 0) max = t;
return max;
}

// Generic method to print list


public static <T> void printList(List<T> list) {
for(T item : list) [Link](item + ' ');
[Link]();
}

// Bounded generic: only Number types


public static <T extends Number> double sum(List<T> list) {
double total = 0;
for(T t : list) total += [Link]();
return total;
}
}

public class GenericsDemo {


public static void main(String[] args) {
Box<Integer> intBox = new Box<>(42);
Box<String> strBox = new Box<>('Hello');
[Link](intBox + ', ' + strBox);

Pair<String, Integer> pair = new Pair<>('Alice', 30);


[Link]('Pair: ' + pair);

Integer[] nums = {3, 7, 1, 9, 4};


[Link]('Max: ' + [Link](nums));

List<Integer> numList = [Link](1, 2, 3, 4, 5);


[Link]('Sum: ' + [Link](numList));
}
}

2 Marks: Type Erasure


Java implements generics via type erasure: generic type information is removed at runtime. At runtime,
Box<Integer> and Box<String> are both just Box. This maintains backward compatibility with pre-
generics code.

Java Internal Exam Answer Bank | Page 17 of 39


PART 3: Java Collections Framework
Q9. Collection Comparisons: List, Set, and Map
[20 Marks]

Introduction (2 Marks)
The Java Collections Framework (JCF) provides a unified architecture for storing and manipulating
groups of objects. The three core interfaces are List, Set, and Map.

1. Comparison Table (4 Marks)


List: Ordered, allows duplicates, index-based access. Implementations: ArrayList, LinkedList, Vector.
Set: Unordered (except LinkedHashSet/TreeSet), unique elements only. Implementations: HashSet,
LinkedHashSet, TreeSet.
Map: Key-value pairs, keys are unique, values can repeat. Not a true Collection. Implementations:
HashMap, LinkedHashMap, TreeMap.

2. Java Program (12 Marks)


import [Link].*;

public class CollectionComparison {


public static void main(String[] args) {
// === LIST ===
[Link]('--- LIST (ArrayList) ---');
List<String> list = new ArrayList<>();
[Link]('Apple'); [Link]('Banana'); [Link]('Apple');
[Link](1, 'Cherry'); // Insert at index
[Link]('List: ' + list); // [Apple, Cherry, Banana, Apple]
[Link]('Index 1: ' + [Link](1)); // Cherry
[Link]('Contains Apple: ' + [Link]('Apple'));
[Link]('Apple'); // Removes first occurrence
[Link]('After remove: ' + list);

// === SET ===


[Link]('\n--- SET (HashSet) ---');
Set<String> set = new HashSet<>();
[Link]('Apple'); [Link]('Banana'); [Link]('Apple'); // Duplicate ignored
[Link]('Set: ' + set); // Order not guaranteed
[Link]('Size: ' + [Link]()); // 2 (no duplicate)

Set<String> linkedSet = new LinkedHashSet<>([Link]('C', 'A', 'B'));


[Link]('LinkedHashSet (insertion order): ' + linkedSet);

Set<String> treeSet = new TreeSet<>([Link]('C', 'A', 'B'));


[Link]('TreeSet (sorted): ' + treeSet);

// === MAP ===


[Link]('\n--- MAP (HashMap) ---');
Map<String, Integer> map = new HashMap<>();

Java Internal Exam Answer Bank | Page 18 of 39


[Link]('Alice', 30); [Link]('Bob', 25); [Link]('Charlie', 35);
[Link]('Alice', 31); // Overwrites existing key
[Link]('Map: ' + map);
[Link]('Alice age: ' + [Link]('Alice'));
[Link]('Contains Bob: ' + [Link]('Bob'));
[Link]('Bob');

// Iterate map
[Link]('Entries:');
for([Link]<String, Integer> entry : [Link]()) {
[Link](' ' + [Link]() + ' -> ' + [Link]());
}

// getOrDefault, putIfAbsent
[Link]('Dave age: ' + [Link]('Dave', -1));
[Link]('Eve', 28);
[Link]('After putIfAbsent: ' + map);
}
}

2 Marks: When to Use Which?


Use List when order and duplicates matter. Use Set when uniqueness is required. Use Map when data
is naturally key-value paired (like a dictionary or database record lookup).

Java Internal Exam Answer Bank | Page 19 of 39


Q10. Data Management with ArrayList, HashSet, HashMap
[20 Marks]

Introduction (2 Marks)
This question demonstrates practical use of core collection classes to store and manage employee
records, showcasing CRUD operations.

Java Program: Employee Record Management (16 Marks)


import [Link].*;

class Employee {
private int id; private String name; private String dept; private double salary;

public Employee(int id, String name, String dept, double salary) {


[Link] = id; [Link] = name; [Link] = dept; [Link] = salary;
}
public int getId() { return id; }
public String getName() { return name; }
public String getDept() { return dept; }
public double getSalary() { return salary; }
public void setSalary(double s) { [Link] = s; }

@Override
public String toString() {
return [Link]('[%d] %s | %s | Rs.%.2f', id, name, dept, salary);
}
}

public class EmployeeManager {


// List: maintain insertion order
static List<Employee> empList = new ArrayList<>();
// HashSet: track unique departments
static Set<String> deptSet = new HashSet<>();
// HashMap: fast lookup by ID
static Map<Integer, Employee> empMap = new HashMap<>();

static void addEmployee(Employee e) {


[Link](e);
[Link]([Link]());
[Link]([Link](), e);
[Link]('Added: ' + [Link]());
}

static Employee findById(int id) {


return [Link](id, null);
}

static void updateSalary(int id, double newSalary) {


Employee e = [Link](id);
if(e != null) { [Link](newSalary); [Link]('Updated: ' + e); }
else [Link]('Employee not found: ' + id);

Java Internal Exam Answer Bank | Page 20 of 39


}

static void removeEmployee(int id) {


Employee e = [Link](id);
if(e != null) { [Link](e); [Link]('Removed: ' +
[Link]()); }
}

static void displayAll() {


[Link]('\n=== All Employees ===');
[Link]([Link]::println);
[Link]('Departments: ' + deptSet);
}

public static void main(String[] args) {


addEmployee(new Employee(1, 'Alice', 'IT', 75000));
addEmployee(new Employee(2, 'Bob', 'HR', 60000));
addEmployee(new Employee(3, 'Charlie', 'IT', 80000));
addEmployee(new Employee(4, 'Diana', 'Finance', 70000));

displayAll();

[Link]('\nFind by ID 2: ' + findById(2));


updateSalary(1, 85000);
removeEmployee(3);

displayAll();
}
}

2 Marks: Why Use All Three?


ArrayList preserves order for display. HashSet efficiently tracks unique departments (no duplicates,
O(1) operations). HashMap provides O(1) employee lookup by ID, essential for performance at scale.

Java Internal Exam Answer Bank | Page 21 of 39


Q11. Set Interface and HashSet
[20 Marks]

Introduction (2 Marks)
The Set interface in Java represents a collection that contains no duplicate elements. It models the
mathematical set abstraction. HashSet is the most commonly used implementation.

1. Set Interface (4 Marks)


Key methods: add(), remove(), contains(), size(), iterator(), isEmpty(), clear().
Set doesn't provide index-based access (unlike List). Implementations: HashSet, LinkedHashSet,
TreeSet, EnumSet.

2. HashSet Internals (4 Marks)


HashSet internally uses a HashMap. When you add an element, it's stored as the key in the backing
HashMap with a dummy constant value (PRESENT).
Uniqueness is determined by hashCode() and equals(). Two objects are considered duplicates if their
hashCode() is equal AND equals() returns true.
Initial capacity: 16, Load factor: 0.75. When 75% full, rehashing doubles the capacity.

3. Java Program (8 Marks)


import [Link].*;

class Student {
String name; int rollNo;
Student(String name, int rollNo) { [Link] = name; [Link] = rollNo; }

@Override
public int hashCode() { return rollNo; }

@Override
public boolean equals(Object o) {
if(this == o) return true;
if(!(o instanceof Student)) return false;
return [Link] == ((Student) o).rollNo;
}

public String toString() { return name + '(Roll:' + rollNo + ')'; }


}

public class SetHashSetDemo {


public static void main(String[] args) {
Set<Integer> numSet = new HashSet<>([Link](5, 3, 1, 4, 2, 3, 1));
[Link]('HashSet (no duplicates): ' + numSet);

// Set operations
Set<Integer> a = new HashSet<>([Link](1,2,3,4,5));
Set<Integer> b = new HashSet<>([Link](3,4,5,6,7));

Java Internal Exam Answer Bank | Page 22 of 39


Set<Integer> union = new HashSet<>(a); [Link](b);
Set<Integer> intersection = new HashSet<>(a); [Link](b);
Set<Integer> diff = new HashSet<>(a); [Link](b);

[Link]('Union: ' + union);


[Link]('Intersection: ' + intersection);
[Link]('Difference A-B: ' + diff);

// Custom objects with hashCode+equals


Set<Student> students = new HashSet<>();
[Link](new Student('Alice', 101));
[Link](new Student('Bob', 102));
[Link](new Student('Alice2', 101)); // Duplicate roll no
[Link]('Students: ' + students); // Only 2 entries
}
}

2 Marks: Contract
For custom objects in HashSet, always override both hashCode() and equals() consistently. Violation
causes incorrect behavior (duplicates stored or elements not found).

Java Internal Exam Answer Bank | Page 23 of 39


Q12. HashMap Operations
[20 Marks]

Introduction (2 Marks)
HashMap stores data as key-value pairs. It provides O(1) average time for get and put operations. It
allows one null key and multiple null values. It is not synchronized.

1. Internal Working (4 Marks)


HashMap uses an array of 'buckets'. The bucket index for a key is computed as: index =
hashCode(key) & (capacity - 1).
Collision handling: Java 8+ uses linked lists for small bucket sizes, then converts to balanced red-black
trees when a bucket exceeds 8 entries (TREEIFY_THRESHOLD).

2. Key Methods (2 Marks)


put(k,v), get(k), remove(k), containsKey(k), containsValue(v), size(), keySet(), values(), entrySet(),
getOrDefault(k, default), putIfAbsent(k,v), compute(k, fn), merge(k,v,fn).

3. Java Program (10 Marks)


import [Link].*;
import [Link].*;

public class HashMapDemo {


public static void main(String[] args) {
// Basic operations
Map<String, Integer> scores = new HashMap<>();
[Link]('Alice', 85); [Link]('Bob', 92);
[Link]('Charlie', 78); [Link]('Diana', 92);
[Link]('Alice', 90); // Overwrites

[Link]('Map: ' + scores);


[Link]('Alice score: ' + [Link]('Alice'));
[Link]('Eve score: ' + [Link]('Eve', 0));

// Iteration methods
[Link]('Keys: ' + [Link]());
[Link]('Values: ' + [Link]());

// forEach
[Link]((k, v) -> [Link](k + ': ' + v));

// compute: update score


[Link]('Bob', (k, v) -> v + 5);
[Link]('Bob updated: ' + [Link]('Bob'));

// merge: add bonus


[Link]('Charlie', 10, Integer::sum);
[Link]('Charlie merged: ' + [Link]('Charlie'));

// Word frequency count

Java Internal Exam Answer Bank | Page 24 of 39


String text = 'apple banana apple cherry banana apple';
Map<String, Long> freq = [Link]([Link](' '))
.collect([Link](w -> w, [Link]()));
[Link]('Word frequency: ' + freq);

// Sort by value
[Link]().stream()
.sorted([Link].<String, Integer>comparingByValue().reversed())
.forEach(e -> [Link]([Link]() + ': ' + [Link]()));
}
}

2 Marks: HashMap vs Hashtable


HashMap is unsynchronized (faster), allows null keys/values. Hashtable is synchronized (thread-safe),
no null keys/values. For thread-safe operations, prefer ConcurrentHashMap over Hashtable.

Java Internal Exam Answer Bank | Page 25 of 39


Q13. TreeSet Internal Logic and Sorted Order
[20 Marks]

Introduction (2 Marks)
TreeSet is a NavigableSet implementation backed by a TreeMap. It stores elements in sorted
(ascending) order using a Red-Black Tree data structure, guaranteeing O(log n) time for basic
operations.

1. Red-Black Tree (5 Marks)


A Red-Black Tree is a self-balancing BST with these properties:
1. Every node is Red or Black.
2. The root is Black.
3. Red nodes cannot have Red children.
4. Every path from root to NULL has the same number of Black nodes.
These properties ensure the tree height is O(log n), guaranteeing O(log n) add/remove/contains.

2. Sorting Mechanisms (3 Marks)


Natural Ordering: Elements implement Comparable<T>. compareTo() is used.
Custom Ordering: A Comparator<T> is passed to the TreeSet constructor.
Note: TreeSet uses compareTo/compare instead of equals for ordering. If compareTo returns 0,
elements are considered duplicates.

3. Java Program (8 Marks)


import [Link].*;

class Product implements Comparable<Product> {


String name; double price;
Product(String name, double price) { [Link] = name; [Link] = price; }

@Override
public int compareTo(Product other) {
return [Link]([Link], [Link]);
}

public String toString() { return name + '(Rs.' + price + ')'; }


}

public class TreeSetDemo {


public static void main(String[] args) {
// Natural ordering (Integer implements Comparable)
TreeSet<Integer> numSet = new TreeSet<>([Link](5,1,8,3,9,2,7,4,6));
[Link]('Sorted: ' + numSet);
[Link]('First: ' + [Link]() + ', Last: ' + [Link]());
[Link]('HeadSet(<5): ' + [Link](5));
[Link]('TailSet(>=5): ' + [Link](5));
[Link]('SubSet(3,7): ' + [Link](3, 7));
[Link]('Floor(4): ' + [Link](4)); // <=4

Java Internal Exam Answer Bank | Page 26 of 39


[Link]('Ceiling(4): ' + [Link](4)); // >=4

// Custom Comparator: sort strings by length


TreeSet<String> byLength = new TreeSet<>(

[Link](String::length).thenComparing([Link]())
);
[Link]([Link]('banana', 'fig', 'apple', 'kiwi', 'date'));
[Link]('By length: ' + byLength);

// Custom Comparable class


TreeSet<Product> products = new TreeSet<>();
[Link](new Product('Laptop', 45000));
[Link](new Product('Phone', 15000));
[Link](new Product('Tablet', 25000));
[Link]('Products sorted by price: ' + products);
}
}

2 Marks: TreeSet vs HashSet


TreeSet: O(log n) operations, sorted, NavigableSet features (floor, ceiling, headSet). HashSet: O(1)
average, unordered. Use TreeSet when sorted order or range operations are needed.

Java Internal Exam Answer Bank | Page 27 of 39


PART 4: GUI Programming (AWT & Swing)
Q14. Layout Managers & Form Design with AWT/Swing
[20 Marks]

Introduction (2 Marks)
AWT (Abstract Window Toolkit) and Swing are Java's GUI frameworks. Layout Managers control how
components are arranged in a container. GridLayout places components in a rectangular grid.

1. Common Layout Managers (4 Marks)


• FlowLayout: Places components left-to-right, wraps to next row. Default for JPanel.
• BorderLayout: 5 regions (North, South, East, West, Center). Default for JFrame.
• GridLayout: Equal-sized grid cells. Components fill row by row.
• GridBagLayout: Most flexible, uses constraints for fine-grained positioning.
• BoxLayout: Places components in a row or column.

2. Java Program: GridLayout Form (12 Marks)


import [Link].*;
import [Link].*;

public class FormDemo extends JFrame {


public FormDemo() {
setTitle('Student Registration Form');
setSize(400, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Main panel with GridLayout


JPanel formPanel = new JPanel(new GridLayout(6, 2, 10, 10));
[Link]([Link](20, 20, 20, 20));

// Name
[Link](new JLabel('Name:'));
JTextField nameField = new JTextField(20);
[Link](nameField);

// Roll Number
[Link](new JLabel('Roll Number:'));
JTextField rollField = new JTextField(20);
[Link](rollField);

// Department
[Link](new JLabel('Department:'));
String[] depts = {'CS', 'IT', 'ECE', 'Mech'};
JComboBox<String> deptBox = new JComboBox<>(depts);
[Link](deptBox);

// Gender

Java Internal Exam Answer Bank | Page 28 of 39


[Link](new JLabel('Gender:'));
JPanel genderPanel = new JPanel(new FlowLayout([Link]));
JRadioButton male = new JRadioButton('Male');
JRadioButton female = new JRadioButton('Female');
ButtonGroup bg = new ButtonGroup();
[Link](male); [Link](female);
[Link](male); [Link](female);
[Link](genderPanel);

// Buttons
JButton submitBtn = new JButton('Submit');
JButton resetBtn = new JButton('Reset');
[Link](submitBtn);
[Link](resetBtn);

// Output label
JLabel outputLabel = new JLabel('', [Link]);
[Link](new JLabel('Output:'));
[Link](outputLabel);

// Event handling inline


[Link](e -> {
String genderStr = [Link]() ? 'Male' : 'Female';
[Link]([Link]() + ' | ' +
[Link]());
[Link](this, 'Registered: ' + [Link]());
});
[Link](e -> {
[Link](''); [Link]('');
[Link](); [Link]('');
});

add(formPanel);
setVisible(true);
}

public static void main(String[] args) {


[Link](FormDemo::new);
}
}

2 Marks: EDT
All Swing UI updates must be done on the Event Dispatch Thread (EDT). Use
[Link]() to schedule GUI creation on the EDT safely.

Java Internal Exam Answer Bank | Page 29 of 39


Q15. The Color Class in AWT
[20 Marks]

Introduction (2 Marks)
The [Link] class represents colors using RGB (Red, Green, Blue) and RGBA (with Alpha for
transparency) color models. It is used to customize the appearance of AWT and Swing components.

1. Constructors and Predefined Colors (4 Marks)


• new Color(int r, int g, int b): RGB values 0–255.
• new Color(int r, int g, int b, int alpha): With transparency (0=transparent, 255=opaque).
• new Color(float r, float g, float b): Float values 0.0–1.0.
• Predefined: [Link], [Link], [Link], [Link], [Link], [Link],
[Link], [Link], [Link], [Link].

2. Key Methods (2 Marks)


getRed(), getGreen(), getBlue(), getAlpha(), brighter(), darker(), toString(), equals().

3. Java Program (10 Marks)


import [Link].*;
import [Link].*;

public class ColorDemo extends JFrame {


public ColorDemo() {
setTitle('Color Class Demo');
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

JPanel panel = new JPanel() {


@Override
protected void paintComponent(Graphics g) {
[Link](g);

// Custom colors
Color skyBlue = new Color(135, 206, 235);
Color saffron = new Color(255, 153, 51);
Color indiaGreen = new Color(19, 136, 8);
Color gold = new Color(255, 215, 0);
Color semiTransparent = new Color(0, 0, 255, 100);

// Draw filled rectangles


[Link](skyBlue);
[Link](20, 20, 120, 80);
[Link]([Link]);
[Link]('Sky Blue', 35, 65);

[Link](saffron);
[Link](160, 20, 120, 80);

Java Internal Exam Answer Bank | Page 30 of 39


[Link]([Link]);
[Link]('Saffron', 195, 65);

[Link](indiaGreen);
[Link](300, 20, 120, 80);
[Link]([Link]);
[Link]('India Green', 310, 65);

// Brighter/Darker
[Link](gold);
[Link](20, 120, 120, 60);
[Link]([Link]());
[Link](160, 120, 120, 60);
[Link]([Link]());
[Link](300, 120, 120, 60);
[Link]([Link]);
[Link]('Gold / Brighter / Darker', 20, 200);

// Semi-transparent rectangle
Graphics2D g2d = (Graphics2D) g;
[Link](semiTransparent);
[Link](100, 220, 200, 100);
[Link]([Link]);
[Link]('Semi-transparent Blue Oval (alpha=100)', 60, 340);
}
};

add(panel);
setVisible(true);
}

public static void main(String[] args) {


[Link](ColorDemo::new);
}
}

2 Marks: HSB/HSL
[Link](float h, float s, float b) creates colors using Hue-Saturation-Brightness model.
[Link]() and [Link]() allow conversions between models.

Java Internal Exam Answer Bank | Page 31 of 39


Q16. Event Handling: KeyListener and ActionListener
[20 Marks]

Introduction (2 Marks)
Event Handling in Java follows the Delegation Event Model: a source component generates an event,
which is dispatched to registered listener(s) that handle it. Listeners are interfaces with callback
methods.

1. Event Handling Model (3 Marks)


Three participants:
1. Event Source: The component that generates the event (Button, TextField, etc.).
2. Event Object: Encapsulates information about the event (ActionEvent, KeyEvent, MouseEvent, etc.).
3. Event Listener: Interface implemented to handle the event (ActionListener, KeyListener,
MouseListener, etc.).
Register: [Link](listener).

2. Java Program (13 Marks)


import [Link].*;
import [Link].*;
import [Link].*;

public class EventHandlingDemo extends JFrame implements ActionListener, KeyListener {


JTextField inputField;
JTextArea outputArea;
JButton submitBtn, clearBtn;
JLabel keyLabel;
int keyCount = 0, clickCount = 0;

public EventHandlingDemo() {
setTitle('Event Handling Demo');
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));

// Top: input and buttons


JPanel topPanel = new JPanel(new FlowLayout());
inputField = new JTextField(20);
submitBtn = new JButton('Submit');
clearBtn = new JButton('Clear');
[Link](new JLabel('Input:'));
[Link](inputField);
[Link](submitBtn);
[Link](clearBtn);

// Center: output
outputArea = new JTextArea(8, 40);
[Link](false);
[Link](new Color(245, 245, 245));

Java Internal Exam Answer Bank | Page 32 of 39


// Bottom: key info
keyLabel = new JLabel('Keystroke info will appear here', [Link]);
[Link]([Link]);

add(topPanel, [Link]);
add(new JScrollPane(outputArea), [Link]);
add(keyLabel, [Link]);

// Register ActionListeners
[Link](this);
[Link](this);

// Register KeyListener on inputField


[Link](this);

// Anonymous inner class for Enter key


[Link](e ->
[Link]('Enter pressed: ' + [Link]() + '\n')
);

setLocationRelativeTo(null);
setVisible(true);
}

// ActionListener implementation
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
if([Link]() == submitBtn) {
String text = [Link]().trim();
if(![Link]()) {
[Link]('Submitted [Click #' + clickCount + ']: ' + text +
'\n');
[Link]('');
}
} else if([Link]() == clearBtn) {
[Link]('');
keyCount = 0; clickCount = 0;
}
}

// KeyListener implementation
@Override
public void keyTyped(KeyEvent e) {
keyCount++;
[Link]('Typed: [' + [Link]() + '] | Total keys: ' + keyCount);
}

@Override
public void keyPressed(KeyEvent e) {
if([Link]() == KeyEvent.VK_ESCAPE) {
[Link]('ESC pressed - field cleared');
[Link]('');
}

Java Internal Exam Answer Bank | Page 33 of 39


}

@Override
public void keyReleased(KeyEvent e) { /* optional */ }

public static void main(String[] args) {


[Link](EventHandlingDemo::new);
}
}

2 Marks: Lambda Listeners


Since Java 8, functional interfaces like ActionListener can be implemented using lambda expressions:
[Link](e -> [Link]('Clicked!')), making code more concise.

Java Internal Exam Answer Bank | Page 34 of 39


PART 5: Advanced Java Concepts
Q17. Java Frameworks: Spring, Hibernate, Struts, JSF
[20 Marks]

Introduction (2 Marks)
Java frameworks provide reusable structures for building enterprise applications. They reduce
boilerplate code, enforce design patterns, and provide out-of-the-box solutions for common enterprise
challenges like persistence, MVC, and dependency management.

1. Spring Framework (5 Marks)


Purpose:
The most popular Java enterprise framework. Provides comprehensive infrastructure support for
developing Java applications.
Core Concepts:
• IoC (Inversion of Control): Spring manages object creation and lifecycle through the IoC container
(ApplicationContext/BeanFactory). Dependencies are injected, not created by the developer.
• DI (Dependency Injection): Objects receive their dependencies via constructor injection or setter
injection, promoting loose coupling.
• AOP (Aspect-Oriented Programming): Cross-cutting concerns (logging, security, transactions) are
separated into Aspects.
Key Modules:
Spring Core, Spring MVC (web), Spring Boot (auto-configuration), Spring Data (JPA/Hibernate), Spring
Security, Spring Cloud (microservices).
Example Use:
Spring Boot allows creating standalone production-grade web apps with embedded servers (Tomcat)
and auto-configuration, drastically reducing boilerplate.

2. Hibernate (5 Marks)
Purpose:
An Object-Relational Mapping (ORM) framework that maps Java objects to relational database tables,
eliminating most JDBC boilerplate.
Core Concepts:
• ORM: Java class ↔ Database table. Java field ↔ DB column. HQL (Hibernate Query Language) ↔
SQL.
• Session: The main runtime interface for DB operations (save, get, update, delete, createQuery).
• SessionFactory: Created once per application, thread-safe factory for Session objects.
• Caching: First-level (Session scope, default) and second-level (SessionFactory scope, optional:
EHCache, Redis).
Annotations (JPA):
@Entity, @Table, @Id, @Column, @OneToMany, @ManyToOne, @GeneratedValue.
Advantage:

Java Internal Exam Answer Bank | Page 35 of 39


Database-independent HQL queries, automatic DDL generation, lazy/eager loading of associations.

3. Struts Framework (4 Marks)


Purpose:
A MVC-based web framework (originally the most popular before Spring MVC). Based on the Front
Controller pattern.
Core Concepts:
• ActionServlet: The front controller that dispatches all HTTP requests.
• Action: Business logic handler class (extends Action or uses annotations in Struts 2).
• [Link] (Struts 1) / [Link] (Struts 2): Maps URLs to Actions and results.
• OGNL (Object-Graph Navigation Language): Used in Struts 2 for expression language in JSPs.
Status:
Largely superseded by Spring MVC, but still used in legacy enterprise systems.

4. JSF – JavaServer Faces (2 Marks)


Purpose:
A component-based UI framework, part of Java EE/Jakarta EE specification. Provides reusable UI
components (PrimeFaces, RichFaces).
Key Features:
• Managed Beans: Server-side beans bound to UI components via EL (Expression Language).
• Facelets: XHTML-based view templates replacing JSP.
• Navigation: Declarative navigation rules in [Link].

2 Marks: Comparison Summary


Spring: Full-stack, IoC/DI/AOP, microservices. Hibernate: ORM for DB. Struts: Legacy MVC. JSF:
Component-based UI (EE standard). In modern development, Spring Boot + Spring Data JPA (with
Hibernate) is the dominant stack.

Java Internal Exam Answer Bank | Page 36 of 39


Q18. Core Adjoint Framework
[20 Marks]

Introduction (2 Marks)
The Core Adjoint Framework refers to utilizing foundational Java frameworks such as the Collections
Framework, Streams API, and Executor Framework together as a cohesive set of tools for building
robust, efficient Java applications.

1. Java Executor Framework (5 Marks)


The [Link] package provides a high-level thread management framework.
Key interfaces: Executor, ExecutorService, ScheduledExecutorService.
Key classes: ThreadPoolExecutor, Executors (factory), ScheduledThreadPoolExecutor.

2. Java Program: Executor + Collections + Streams (11 Marks)


import [Link].*;
import [Link].*;
import [Link].*;

public class CoreFrameworkDemo {


// Task implementing Callable
static class DataProcessTask implements Callable<String> {
private String data;
DataProcessTask(String data) { [Link] = data; }

@Override
public String call() throws Exception {
[Link](100); // Simulate processing
return [Link]() + ' [processed by ' +
[Link]().getName() + ']';
}
}

public static void main(String[] args) throws Exception {


// 1. Collections
List<String> items = [Link]('apple', 'banana', 'cherry', 'date',
'elderberry');

// 2. Streams API
[Link]('--- Streams Processing ---');
List<String> filtered = [Link]()
.filter(s -> [Link]() > 5)
.map(String::toUpperCase)
.sorted()
.collect([Link]());
[Link]('Filtered & Sorted: ' + filtered);

Map<Integer, List<String>> grouped = [Link]()


.collect([Link](String::length));
[Link]('Grouped by length: ' + grouped);

Java Internal Exam Answer Bank | Page 37 of 39


OptionalDouble avg = [Link]().mapToInt(String::length).average();
[Link]('Avg length: %.2f%n', [Link]());

// 3. Executor Framework
[Link]('\n--- Executor Framework ---');
ExecutorService executor = [Link](3);

List<Future<String>> futures = new ArrayList<>();


for(String item : items) {
[Link]([Link](new DataProcessTask(item)));
}

for(Future<String> future : futures) {


[Link]([Link]()); // Blocks until result ready
}

[Link]();

// 4. Scheduled Executor
ScheduledExecutorService scheduler = [Link](1);
[Link](() -> [Link]('Scheduled task ran!'), 1,
[Link]);
[Link]();
[Link](5, [Link]);

// 5. CompletableFuture (modern async)


[Link]('\n--- CompletableFuture ---');
CompletableFuture<String> cf = CompletableFuture
.supplyAsync(() -> 'Hello')
.thenApply(s -> s + ', World')
.thenApply(String::toUpperCase);
[Link]('CompletableFuture result: ' + [Link]());
}
}

2 Marks: Why Use Executors over Threads?


Thread creation is expensive. ExecutorService manages a thread pool, reusing threads for multiple
tasks. This reduces overhead, prevents resource exhaustion from unbounded thread creation, and
provides lifecycle management (shutdown, awaitTermination).

Java Internal Exam Answer Bank | Page 38 of 39


— End of Answer Bank —

Java Internal Exam Answer Bank | Page 39 of 39

You might also like