⚡ CCSU Meerut · BCA 5th Semester · Exam Preparation
Java Programming & Web Design BCA-502 Most Important Questions & Solved Exam Notebook
Master solved question bank of recurring CCSU examination questions (2014–2023) for Java Programming & Dynamic Webpage Design (BCA-502) with JVM architecture, multithreading, custom exceptions, Swing GUI calculator, and vector SVG diagrams.
Very Short Answer Questions & Core Java Fundamentals
CCSU Examination Blueprint: 5 Questions Compulsory • Total 15 Marks (75 Words Limit)
Q1. Why is Java called a "Platform Independent" language? Explain the WORA philosophy.
Java is platform independent because its source code (.java) is not compiled directly into machine-specific native binary. Instead, the Java Compiler (javac) converts source code into an intermediate, architecture-neutral format called Bytecode (.class file).
This bytecode cannot be run directly by the host operating system's CPU. Instead, any machine with a platform-specific Java Virtual Machine (JVM) can execute this bytecode. Hence, the philosophy: "Write Once, Run Anywhere" (WORA). While the bytecode is platform-independent, the JVM itself is platform-dependent (different JVM binaries exist for Windows, Linux, and macOS).
Q2. Differentiate between JDK, JRE, and JVM with their primary roles.
| Component | Full Name | Definition & Inclusions |
|---|---|---|
| JVM | Java Virtual Machine | Abstract computing machine that loads, verifies, and executes bytecode. Provides runtime environment and memory management (Garbage Collector). |
| JRE | Java Runtime Environment | Software package required to run already compiled Java programs. Contains JVM + Core Class Libraries (rt.jar). Contains no compilers or debuggers. |
| JDK | Java Development Kit | Full-featured software development environment required to develop and compile Java applications. Contains JRE + Development Tools (javac, java, javadoc, jdb). |
JDK = JRE + Development Tools • JRE = JVM + Class Libraries.
Q3. Explain the significance of each keyword in: public static void main(String[] args).
public: An access modifier making the main method globally accessible from anywhere, allowing the external JVM runtime to invoke it from outside its class/package.static: Allows the JVM to invoke the method directly using the class name (ClassName.main()) without needing to instantiate an object of that class first.void: Return type indicating the method does not return any exit status value to the caller upon completion.main: The fixed identifier name searched by the JVM as the mandatory starting entry point of any standalone Java application.String[] args: An array ofStringobjects representing command-line arguments passed into the program during terminal execution (e.g.java App file1 20).
Q4. Why does Java not support explicit pointer arithmetic like C/C++?
Java deliberately omitted direct pointer manipulation for three vital engineering reasons:
- Security: Direct pointer manipulation allows rogue code to inspect and corrupt arbitrary physical memory addresses, bypassing operating system firewalls and JVM sandboxing.
- Memory Safety & Robustness: In C/C++, uninitialized pointers or dangling pointers cause catastrophic segmentation faults, buffer overflows, and memory leaks. Java replaces pointers with managed references.
- Automatic Garbage Collection: For Java's automatic Garbage Collector (GC) to safely relocate objects in heap memory during memory compaction, objects cannot be bound to fixed physical memory addresses through raw pointers.
Q5. What is Constructor Overloading in Java? Provide a concise code example.
Constructor Overloading is a technique having multiple constructors within the same class, each having the same name (the class name) but differing in the number, type, or sequence of parameters. The compiler determines which constructor to invoke based on the arguments supplied during object instantiation.
class Box {
double width, height, depth;
// Default Constructor
Box() { width = height = depth = 10; }
// Parameterized Constructor (Cube)
Box(double len) { width = height = depth = len; }
// Parameterized Constructor (Cuboid)
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
}
Q6. Differentiate between this and super keywords in Java.
| Feature | this Keyword |
super Keyword |
|---|---|---|
| Reference Target | Refers to the current class object instance. | Refers to the immediate superclass (parent) object instance. |
| Variable Access | Resolves shadowing between instance variables and local parameters (e.g. this.name = name;). |
Accesses hidden parent class fields when shadowed by child class fields (e.g. super.salary;). |
| Constructor Call | this(...) invokes an overloaded constructor of the same class (constructor chaining). |
super(...) invokes the constructor of the parent class. Must be the first statement! |
| Method Call | Invokes current class instance methods. | Invokes overridden parent class methods (e.g. super.display();). |
Q7. Why does Java not support Multiple Inheritance through classes? How does it resolve the issue?
Java forbids multiple inheritance through classes to prevent the notorious Diamond Problem (Ambiguity Error). If class C extends both class A and class B, and both A and B define a method display() with different implementations, class C cannot resolve which version to execute, resulting in compile-time ambiguity.
Java's Resolution: Java achieves multiple inheritance exclusively through Interfaces. Since interface methods are abstract contracts (they contain no instance variable state), a class implementing multiple interfaces provides its own single, concrete implementation, completely eradicating ambiguity.
Q8. Contrast Method Overloading and Method Overriding.
| Criteria | Method Overloading (Compile-Time) | Method Overriding (Run-Time) |
|---|---|---|
| Scope | Occurs within the same class. | Occurs across parent and child classes (Inheritance required). |
| Method Signature | Method name must be identical, but parameter list (count, type) must differ. | Method name, argument list, and return type must be strictly identical. |
| Binding Time | Static / Early binding resolved by compiler at compile-time. | Dynamic / Late binding resolved by JVM at runtime based on object instance. |
| Private/Static/Final | Can overload private, static, and final methods. |
Cannot override private, static, or final methods. |
Q9. Differentiate between final, finally, and finalize() in Java.
final(Keyword): Non-access modifier used to enforce immutability:- Final variable → Constant value that cannot be reassigned.
- Final method → Method that cannot be overridden by subclasses.
- Final class → Class that cannot be extended (subclassed, e.g.
java.lang.String).
finally(Block): Exception handling block placed aftertry-catchthat always executes regardless of whether an exception is thrown or caught (ideal for closing resources, streams, and database connections).finalize()(Method): Protected method defined injava.lang.Objectinvoked by the Garbage Collector just before an unreachable object is physically reclaimed from heap memory for resource cleanup.
Q10. Contrast throw and throws keywords in Java.
| Feature | throw Keyword |
throws Keyword |
|---|---|---|
| Purpose | Used to explicitly trigger/throw an exception object instance. | Used in method signatures to declare that a method may cause an exception. |
| Location | Used inside method bodies: throw new ArithmeticException("Divide by zero"); |
Appended to method declarations: void readFile() throws IOException |
| Syntax | Followed by an exception instance (object). Can throw only one exception at a time. | Followed by exception class names (comma-separated list for multiple checked exceptions). |
Q11. Differentiate between Checked and Unchecked Exceptions in Java.
| Feature | Checked Exceptions | Unchecked Exceptions |
|---|---|---|
| Detection Time | Checked by compiler at compile-time. Program will fail to compile if not caught or declared with throws. |
Occur at runtime. Compiler does not force explicit handling. |
| Inheritance | Direct subclasses of java.lang.Exception (excluding RuntimeException). |
Subclasses of java.lang.RuntimeException and java.lang.Error. |
| Examples | IOException, SQLException, ClassNotFoundException, FileNotFoundException. |
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException. |
Q12. What is the advantage of implementing Runnable interface over extending Thread class?
Implementing the Runnable interface is standard industry best practice for two fundamental reasons:
- Preserves Single Inheritance: Java does not support multiple class inheritance. If a class extends
Thread, it cannot inherit from any other base business class (e.g.Employee,Applet). ImplementingRunnableleaves the class free to extend any other class. - Separation of Task from Runner:
Runnablerepresents the functional task/logic to execute, whileThreadis the worker executing that task. This cleanly decouples business code and allows thread pooling via theExecutorServiceframework.
Q13. Differentiate between Byte Streams and Character Streams in Java I/O.
| Feature | Byte Stream Classes | Character Stream Classes |
|---|---|---|
| Data Unit | Processes data byte by byte (8-bit bytes). | Processes data character by character (16-bit Unicode). |
| Superclasses | InputStream and OutputStream (abstract roots). |
Reader and Writer (abstract roots). |
| Best Suited For | Binary files: images, audio, video, PDF, compiled .class files (e.g. FileInputStream, FileOutputStream). |
Human-readable text files with diverse language character sets (e.g. FileReader, FileWriter). |
Q14. State the five life-cycle callback methods of a Java Applet in sequence.
init(): Invoked once when the applet is first loaded into memory. Used for one-time component initialization and parameter reading.start(): Invoked immediately afterinit()and each time the user navigates back to the browser page containing the applet. Resumes threads/animations.paint(Graphics g): Invoked whenever the applet's display surface must be rendered or repainted.stop(): Invoked whenever the browser page is minimized or navigated away from. Suspends running threads and animations.destroy(): Invoked once just before the applet is completely unloaded from browser memory. Frees allocated native resources.
Q15. What is the Event Delegation Model in Java GUI Programming? Name its three core components.
The Event Delegation Model is a standard event-processing architecture introduced in Java 1.1 wherein a user interface component (Event Source) does not handle user actions directly. Instead, it delegates event processing to registered handler objects called Event Listeners.
- 1. Event Source: The GUI component that generates the event upon user interaction (e.g.
JButton,JTextField,JCheckBox). - 2. Event Object: Encapsulates state information about the event that occurred (e.g.
ActionEvent,MouseEvent,KeyEvent). - 3. Event Listener: An interface containing callback event-handler methods implemented by the listener class (e.g.
ActionListenerwithactionPerformed()).
Analytical Questions, Architectures & Core Implementations
CCSU Examination Blueprint: Attempt Any 2 of 3 Questions • Total 15 Marks (~200 Words + Code/Diagrams)
Q16. Explain the internal Architecture of the Java Virtual Machine (JVM) with a neat block diagram detailing its memory areas and execution engine.
The Java Virtual Machine (JVM) is an abstract computing machine that provides a runtime environment in which Java bytecode can be executed. Its internal architecture consists of three primary subsystems:
Detailed Memory Component Breakdown:
- Method Area: Shared memory storing per-class structures: bytecode instructions, static variables, runtime constant pool, and constructor code.
- Heap Area: Shared runtime memory where all object instances and arrays are allocated. Directly governed by the Garbage Collector.
- JVM Stack: Per-thread private memory holding stack frames created on each method invocation (stores local variables, operand stack, and partial results).
- PC Register: Per-thread register storing the memory address of the JVM bytecode instruction currently being executed.
- Native Method Stack: Holds native method invocation frames written in C/C++.
Q17. What is an Interface in Java? Demonstrate with a complete program how an interface achieves multiple inheritance.
An Interface is a pure abstract blueprint of a class containing constant fields (implicitly public static final) and abstract method declarations (implicitly public abstract). A class uses the implements keyword to inherit interface specifications.
Achieving Multiple Inheritance: A class in Java can implement multiple interfaces simultaneously, separated by commas (implements InterfaceA, InterfaceB), thereby bypassing the single class inheritance restriction.
// Interface 1: Academic Examination
interface Exam {
void showExamMarks();
}
// Interface 2: Extracurricular Sports
interface Sports {
void showSportsScore();
}
// Base Student Class
class Student {
int rollNo = 101;
String name = "Aman Kumar";
}
// Child class inheriting Student and implementing two interfaces
class Result extends Student implements Exam, Sports {
int academicMarks = 88;
int sportsScore = 94;
@Override
public void showExamMarks() {
System.out.println("Academic Marks: " + academicMarks);
}
@Override
public void showSportsScore() {
System.out.println("Sports Score: " + sportsScore);
}
public void displayFullReport() {
System.out.println("Roll No: " + rollNo + " | Name: " + name);
showExamMarks();
showSportsScore();
int total = academicMarks + sportsScore;
System.out.println("Composite Total Score: " + total);
}
}
public class MultipleInheritanceDemo {
public static void main(String[] args) {
Result studentReport = new Result();
studentReport.displayFullReport();
}
}
Roll No: 101 | Name: Aman KumarAcademic Marks: 88Sports Score: 94Composite Total Score: 182
Q18. Explain the complete Life Cycle of a Thread in Java with state transitions and thread control methods.
A Java thread is a lightweight subprocess that transitions through distinct operational states governed by the JVM and OS Thread Scheduler:
- New State: Thread object is created (
Thread t = new Thread();) butt.start()has not yet been called. - Runnable State: After
t.start()is invoked. The thread is ready and waiting in the CPU ready queue for thread scheduler assignment. - Running State: Thread scheduler allocates a CPU time slice; the thread executes its
run()method. - Blocked / Waiting / Timed Waiting: Suspended from execution when waiting for a lock, asleep (
Thread.sleep(ms)), or awaiting notification (wait()). Once the lock or event arrives, it returns to Runnable. - Terminated (Dead) State: The thread completes execution of its
run()method or terminates abruptly due to an uncaught fatal exception.
Q19. Explain Exception Handling with try, multiple catch blocks, and finally. In what specific circumstances will a finally block NOT execute?
In Java, a single try block can be followed by multiple catch blocks to handle distinct exception types independently. Rule of Order: Catch blocks must be arranged from most specific subclass to most general superclass (e.g. ArithmeticException before Exception); otherwise, a compile-time "unreachable code" error occurs.
public class MultiCatchDemo {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50 / 0; // Triggers ArithmeticException or ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Handler 1: Math division error -> " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Handler 2: Array indexing out of bounds -> " + e.getMessage());
} catch (Exception e) {
System.out.println("Handler 3: Generic fallback error -> " + e.getMessage());
} finally {
System.out.println("Finally block: Critical cleanup executed successfully.");
}
}
}
Circumstances when the finally block does NOT execute:
- 1. Explicit JVM Shutdown: If
System.exit(0)orRuntime.getRuntime().halt(0)is called inside thetryorcatchblock. - 2. Fatal OS / Hardware Crash: Power failure, OS process kill (
kill -9), or severe hardware malfunction. - 3. Fatal JVM Error: If an unrecoverable
OutOfMemoryError,VirtualMachineError, or native segmentation fault crashes the host JVM. - 4. Infinite Loop / Deadlock: If an infinite loop or indefinite deadlock freezes execution inside the
tryblock before reachingfinally.
Q20. Differentiate between an Abstract Class and an Interface in Java with an exhaustive comparison table.
| Feature | Abstract Class | Interface |
|---|---|---|
| Keyword | Declared using abstract class; extended via extends. |
Declared using interface; implemented via implements. |
| Multiple Inheritance | Does NOT support multiple inheritance (a class can extend only one abstract class). | Fully supports multiple inheritance (a class can implement multiple interfaces). |
| Method Types | Can contain both abstract (unimplemented) and concrete (fully implemented) methods. | Traditionally abstract only. (Java 8+ allows default and static methods; Java 9+ allows private methods). |
| Variables / Fields | Can have instance variables, final, non-final, static, and non-static variables. | Fields are strictly and implicitly public static final (constants only). |
| Constructors | Has constructors invoked during subclass constructor chaining (via super()). |
Cannot have constructors because interfaces cannot maintain instance state. |
| Access Modifiers | Can have private, protected, default, and public members. |
Interface members are implicitly public by default. |
| Design Goal | Defines an "is-a" identity relationship with shared code base. | Defines a "can-do" contract / capability without tying to class hierarchy. |
Q21. What are Packages in Java? How do they avoid naming conflicts? Explain Java's four Access Protection specifiers with an access matrix.
A Package is a container / namespace that groups related classes, interfaces, and subpackages together. It maps directly to physical directory structures on disk.
Preventing Naming Conflicts: Two classes with the identical name Date can coexist peacefully in the same application if isolated in separate packages: java.util.Date (represents timestamps) vs java.sql.Date (represents SQL database dates).
The Java Access Protection Matrix:
| Access Specifier | Same Class | Same Package Subclass | Same Package Non-subclass | Different Package Subclass | Different Package Non-subclass (World) |
|---|---|---|---|---|---|
private |
✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
| Default (package-private) | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
protected |
✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes (via inheritance) | ❌ No |
public |
✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
Q22. Differentiate between AWT and Swing components. Explain the role of the three primary Layout Managers: FlowLayout, BorderLayout, and GridLayout.
| Criteria | AWT (Abstract Window Toolkit) | Swing (Java Foundation Classes) |
|---|---|---|
| Component Weight | Heavyweight: Dependent on native OS GUI peers; consumes host OS resources. | Lightweight: Written 100% in pure Java; drawn independently without native OS peers. |
| Look & Feel | Platform-dependent appearance (looks like Windows on Windows, Mac on Mac). | Pluggable Look & Feel (Metal, Nimbus, Windows, Motif) uniform across platforms. |
| Package & Prefix | java.awt.* (e.g. Button, TextField). |
javax.swing.* prefixed with 'J' (e.g. JButton, JTextField). |
| Advanced Features | Lacks tables, trees, tabbed panes, and tooltips. | Includes rich widgets: JTable, JTree, JTabbedPane, JProgressBar. |
Primary Layout Managers:
FlowLayout: Arranges components sequentially in a directional row (left-to-right). When a line fills, components wrap naturally to the next line. (Default forJPanel).BorderLayout: Divides the container into five distinct geographical regions:NORTH,SOUTH,EAST,WEST, andCENTER. Components inCENTERstretch to fill remaining space. (Default forJFrame).GridLayout: Arranges components in an equidistant, rectangular grid of user-defined rows and columns ($R imes C$). Every cell is forced to identical dimensions regardless of component contents. (Ideal for calculators and numeric keypads).
Q23. Write a complete, compilable Java program to copy the contents of a source text file into a destination file using Byte Streams with robust exception handling.
The program uses FileInputStream to read 8-bit raw bytes from the source file and FileOutputStream to write bytes to the target file. It uses Java 7+ try-with-resources to guarantee streams close automatically without memory leaks even if an I/O error occurs.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyProgram {
public static void main(String[] args) {
String sourcePath = "source.txt";
String destPath = "destination.txt";
// Try-with-resources guarantees automatic stream closure
try (FileInputStream inStream = new FileInputStream(sourcePath);
FileOutputStream outStream = new FileOutputStream(destPath)) {
byte[] buffer = new byte[1024]; // 1 KB buffer for high I/O throughput
int bytesRead;
int totalBytes = 0;
// read() returns -1 when end-of-file (EOF) is reached
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
System.out.println("File copied successfully!");
System.out.println("Total bytes transferred: " + totalBytes + " bytes.");
} catch (IOException e) {
System.err.println("I/O Error during file transfer: " + e.getMessage());
}
}
}
inStream.read(buffer)reads up to 1024 bytes into memory at once, reducing expensive disk read hardware interrupts by 1000x compared to single-byte reading.outStream.write(buffer, 0, bytesRead)ensures that only actual bytes read are written out, preventing trailing garbage bytes in the target file.
Master Long Answer Questions, Architectural Blueprints & SVG Diagrams
CCSU Examination Blueprint: Attempt Any 3 of 5 Questions • Total 45 Marks (~500+ Words + Working Code + Diagrams)
Q24. Explain the mechanism of Dynamic Method Dispatch (Runtime Polymorphism) in Java. How does the JVM resolve method calls dynamically? Illustrate with a complete compilable Shape hierarchy program, memory layout, and dry-run output.
1. Concept of Dynamic Method Dispatch
Dynamic Method Dispatch is the fundamental mechanism by which a call to an overridden method is resolved at runtime (dynamically) rather than at compile-time. It is the cornerstone of runtime polymorphism in Java.
The core rule of Dynamic Method Dispatch:
"A superclass reference variable can refer to any subclass object instance. When an overridden method is called through a superclass reference, Java determines which version of the method to execute based on the actual type of the object being referred to at runtime, not the type of the reference variable."
2. Complete Compilable Java Implementation:
// Abstract Base Superclass
abstract class Shape {
String name;
Shape(String name) {
this.name = name;
}
// Abstract method to be overridden by all subclasses
abstract double calculateArea();
// Concrete method common to all shapes
void displayInfo() {
System.out.println("Processing Geometric Shape: " + name);
}
}
// Subclass 1: Circle
class Circle extends Shape {
double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
// Subclass 2: Rectangle
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
super("Rectangle");
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
}
// Subclass 3: Triangle
class Triangle extends Shape {
double base, height;
Triangle(double base, double height) {
super("Triangle");
this.base = base;
this.height = height;
}
@Override
double calculateArea() {
return 0.5 * base * height;
}
}
// Main Execution Class Demonstrating Polymorphism
public class DynamicDispatchMasterDemo {
public static void main(String[] args) {
// Base class reference variable
Shape ref;
// Polymorphic Array of Base References
Shape[] shapeCollection = new Shape[3];
shapeCollection[0] = new Circle(7.0);
shapeCollection[1] = new Rectangle(5.0, 8.0);
shapeCollection[2] = new Triangle(6.0, 10.0);
// Dynamic binding in a loop
for (Shape s : shapeCollection) {
s.displayInfo();
// JVM resolves calculateArea() at runtime based on actual heap object
double area = s.calculateArea();
System.out.printf("Calculated Area: %.2f sq units\n", area);
System.out.println("----------------------------------------------");
}
}
}
3. Execution Trace & Dry-Run Output:
Processing Geometric Shape: CircleCalculated Area: 153.94 sq units----------------------------------------------Processing Geometric Shape: RectangleCalculated Area: 40.00 sq units----------------------------------------------Processing Geometric Shape: TriangleCalculated Area: 30.00 sq units----------------------------------------------
Q25. Discuss Thread Synchronization and Inter-Thread Communication in Java. What are race conditions and object monitors? Solve the classic Producer-Consumer Problem using wait() and notify() with a complete runnable program and state diagram.
1. The Need for Synchronization & Object Monitors
When multiple concurrent threads attempt to access and modify a shared mutable resource (such as a shared bank balance or shared buffer) simultaneously, execution interleaving can cause race conditions where data becomes corrupted and inconsistent.
In Java, every single object has an implicit internal lock called an Intrinsic Lock (or Monitor). A thread that enters a synchronized method or synchronized block automatically acquires that object's monitor. All other threads attempting to access synchronized code on the same object are blocked until the lock is released.
2. Complete Compilable Producer-Consumer Solution:
// Shared Bounded Buffer with Inter-Thread Synchronization
class SharedBuffer {
private int data;
private boolean available = false; // Flag indicating if item is ready to consume
// Synchronized method called by Producer
public synchronized void produce(int value) {
// While buffer is full, producer must wait for consumer to empty it
while (available) {
try {
wait(); // Releases lock and goes to sleep in wait-set
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
data = value;
available = true;
System.out.println("-> [PRODUCED] Data Item: " + data);
notify(); // Wakes up single waiting thread (Consumer)
}
// Synchronized method called by Consumer
public synchronized int consume() {
// While buffer is empty, consumer must wait for producer to fill it
while (!available) {
try {
wait(); // Releases lock and sleeps
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
available = false;
System.out.println("<- [CONSUMED] Data Item: " + data);
notify(); // Wakes up waiting Producer
return data;
}
}
// Producer Worker Thread
class Producer extends Thread {
private SharedBuffer buffer;
Producer(SharedBuffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
buffer.produce(i * 10);
try {
Thread.sleep(400); // Simulate manufacturing work delay
} catch (InterruptedException e) {
break;
}
}
}
}
// Consumer Worker Thread
class Consumer extends Thread {
private SharedBuffer buffer;
Consumer(SharedBuffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
buffer.consume();
try {
Thread.sleep(600); // Simulate processing work delay
} catch (InterruptedException e) {
break;
}
}
}
}
public class ProducerConsumerMasterDemo {
public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer();
Producer p = new Producer(buffer);
Consumer c = new Consumer(buffer);
System.out.println("Starting Producer-Consumer Execution Pipeline...");
p.start();
c.start();
}
}
3. Execution Console Output Trace:
Starting Producer-Consumer Execution Pipeline...-> [PRODUCED] Data Item: 10<- [CONSUMED] Data Item: 10-> [PRODUCED] Data Item: 20<- [CONSUMED] Data Item: 20-> [PRODUCED] Data Item: 30<- [CONSUMED] Data Item: 30-> [PRODUCED] Data Item: 40<- [CONSUMED] Data Item: 40-> [PRODUCED] Data Item: 50<- [CONSUMED] Data Item: 50
Q26. Describe the complete Java Exception Hierarchy. Explain stack unwinding during exception propagation. Write a comprehensive Banking Application demonstrating custom user-defined checked exceptions (InsufficientBalanceException) with deposit and withdrawal validations.
1. Java Exception Hierarchy Blueprint:
2. Stack Unwinding & Exception Propagation:
When an exception is thrown inside a method and not caught locally, the JVM halts execution of that method, unwinds its stack frame from the Call Stack, and passes the exception up to the calling method. This repeats sequentially until a matching catch block is found or the program terminates at the JVM default handler.
3. Complete Banking Application with Custom Exceptions:
// Custom Checked Exception 1: Insufficient Balance
class InsufficientBalanceException extends Exception {
private double balance;
private double requestedAmount;
public InsufficientBalanceException(double balance, double requestedAmount) {
super("Transaction Rejected: Available Balance is ₹" + balance +
", but withdrawal requested is ₹" + requestedAmount);
this.balance = balance;
this.requestedAmount = requestedAmount;
}
}
// Custom Checked Exception 2: Invalid Deposit Amount
class InvalidAmountException extends Exception {
public InvalidAmountException(String message) {
super(message);
}
}
// Bank Account Class
class BankAccount {
private String accountNumber;
private String holderName;
private double balance;
public BankAccount(String accNo, String name, double initialBalance) {
this.accountNumber = accNo;
this.holderName = name;
this.balance = initialBalance;
}
// Method declaring that it throws checked custom exceptions
public void deposit(double amount) throws InvalidAmountException {
if (amount <= 0) {
throw new InvalidAmountException("Deposit amount must be strictly greater than zero! Given: ₹" + amount);
}
balance += amount;
System.out.printf("₹%.2f deposited successfully. Updated Balance: ₹%.2f\n", amount, balance);
}
public void withdraw(double amount) throws InsufficientBalanceException, InvalidAmountException {
if (amount <= 0) {
throw new InvalidAmountException("Withdrawal amount must be greater than zero!");
}
if (amount > balance) {
throw new InsufficientBalanceException(balance, amount);
}
balance -= amount;
System.out.printf("₹%.2f withdrawn successfully. Remaining Balance: ₹%.2f\n", amount, balance);
}
public double getBalance() {
return balance;
}
}
// Main Driver Application
public class BankingExceptionMasterDemo {
public static void main(String[] args) {
BankAccount acc = new BankAccount("CCSU-BCA-9810", "Vikram Rathore", 5000.0);
System.out.println("=== CCSU Banking System Transaction Processing ===");
// Transaction 1: Valid Deposit
try {
acc.deposit(2500.0);
} catch (InvalidAmountException e) {
System.err.println("Deposit Error: " + e.getMessage());
}
// Transaction 2: Invalid Withdrawal (Exceeding Balance)
try {
System.out.println("Attempting withdrawal of ₹9,000.00...");
acc.withdraw(9000.0);
} catch (InsufficientBalanceException e) {
System.err.println("ALARM: " + e.getMessage());
} catch (InvalidAmountException e) {
System.err.println("Error: " + e.getMessage());
} finally {
System.out.printf("Status: Account statement closed. Current Balance: ₹%.2f\n", acc.getBalance());
}
}
}
=== CCSU Banking System Transaction Processing ===₹2500.00 deposited successfully. Updated Balance: ₹7500.00Attempting withdrawal of ₹9,000.00...ALARM: Transaction Rejected: Available Balance is ₹7500.0, but withdrawal requested is ₹9000.0Status: Account statement closed. Current Balance: ₹7500.00
Q27. Contrast Multiple Inheritance in C++ vs Java. How does Java eliminate the "Diamond Problem"? Discuss Java 8 Interface innovations (default and static methods) and how conflicting default methods are resolved with working code.
1. The Diamond Problem in C++ vs Java's Architectural Resolution
In C++, if class B and class C inherit from class A, and class D inherits from both B and C, two duplicate copies of class A's data members reside inside object D. Any invocation of A's methods creates ambiguous conflicts unless complex virtual base classes are used.
Java's Design: Java disallows multiple class inheritance entirely. Classes can only extend one base class, but can implement multiple interfaces. Because interfaces contain no instance state (fields are only constants), no duplicate variable state exists in memory.
2. Resolving Conflicting Default Methods (Java 8+):
If two interfaces define the exact same default method signature, the implementing class must override the method and explicitly specify which interface version to invoke using InterfaceName.super.methodName().
interface Printable {
default void logMessage() {
System.out.println("[Printable Default]: Output sent to physical printer.");
}
}
interface Exportable {
default void logMessage() {
System.out.println("[Exportable Default]: Output converted to PDF document.");
}
}
// Class implementing both interfaces must resolve ambiguity
class DocumentHandler implements Printable, Exportable {
@Override
public void logMessage() {
// Explicit resolution using InterfaceName.super
System.out.println("--- DocumentHandler Resolving Interface Conflict ---");
Printable.super.logMessage(); // Invoke Printable version
Exportable.super.logMessage(); // Invoke Exportable version
}
}
public class InterfaceConflictDemo {
public static void main(String[] args) {
DocumentHandler doc = new DocumentHandler();
doc.logMessage();
}
}
Q28. Explain the Event Delegation Model in Java GUI Programming. Write a complete, compilable Java Swing application implementing a Graphical User Interface (GUI) Arithmetic Calculator with buttons for Addition, Subtraction, Multiplication, Division, Clear, and Result display.
1. The Event Delegation Architecture:
2. Complete Standalone Java Swing Calculator Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingCalculatorApp extends JFrame implements ActionListener {
// GUI Components
private JTextField numField1, numField2, resultField;
private JButton btnAdd, btnSub, btnMul, btnDiv, btnClear;
public SwingCalculatorApp() {
// Window Configuration
setTitle("CCSU BCA Swing Calculator");
setSize(420, 320);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center on screen
setLayout(new BorderLayout(10, 10));
// 1. Title Label (North)
JLabel titleLabel = new JLabel("BCA Arithmetic Calculator", JLabel.CENTER);
titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
titleLabel.setForeground(new Color(2, 132, 199));
add(titleLabel, BorderLayout.NORTH);
// 2. Input Fields Grid (Center)
JPanel inputPanel = new JPanel(new GridLayout(3, 2, 8, 8));
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
inputPanel.add(new JLabel("First Number:"));
numField1 = new JTextField();
inputPanel.add(numField1);
inputPanel.add(new JLabel("Second Number:"));
numField2 = new JTextField();
inputPanel.add(numField2);
inputPanel.add(new JLabel("Calculated Result:"));
resultField = new JTextField();
resultField.setEditable(false); // Read-only output
resultField.setBackground(new Color(241, 245, 249));
inputPanel.add(resultField);
add(inputPanel, BorderLayout.CENTER);
// 3. Action Buttons Panel (South)
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
btnAdd = new JButton("+");
btnSub = new JButton("-");
btnMul = new JButton("*");
btnDiv = new JButton("/");
btnClear = new JButton("Clear");
// Register Action Listeners
btnAdd.addActionListener(this);
btnSub.addActionListener(this);
btnMul.addActionListener(this);
btnDiv.addActionListener(this);
btnClear.addActionListener(this);
buttonPanel.add(btnAdd);
buttonPanel.add(btnSub);
buttonPanel.add(btnMul);
buttonPanel.add(btnDiv);
buttonPanel.add(btnClear);
add(buttonPanel, BorderLayout.SOUTH);
}
// Event Delegation Callback Handler
@Override
public void actionPerformed(ActionEvent e) {
// Clear Button Action
if (e.getSource() == btnClear) {
numField1.setText("");
numField2.setText("");
resultField.setText("");
numField1.requestFocus();
return;
}
try {
double n1 = Double.parseDouble(numField1.getText().trim());
double n2 = Double.parseDouble(numField2.getText().trim());
double result = 0;
if (e.getSource() == btnAdd) {
result = n1 + n2;
} else if (e.getSource() == btnSub) {
result = n1 - n2;
} else if (e.getSource() == btnMul) {
result = n1 * n2;
} else if (e.getSource() == btnDiv) {
if (n2 == 0) {
JOptionPane.showMessageDialog(this, "Arithmetic Error: Cannot divide by zero!",
"Division Error", JOptionPane.ERROR_MESSAGE);
return;
}
result = n1 / n2;
}
resultField.setText(String.format("%.2f", result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid Input: Please enter valid numerical values!",
"Input Error", JOptionPane.WARNING_MESSAGE);
}
}
public static void main(String[] args) {
// Run on Event Dispatch Thread (EDT) for thread safety
SwingUtilities.invokeLater(() -> {
new SwingCalculatorApp().setVisible(true);
});
}
}
Q29. Explain the principles of Object Serialization and Deserialization in Java. What is the role of Serializable interface, serialVersionUID, and the transient keyword? Write a program that writes an object to disk and restores it.
1. Serialization Architecture & Key Concepts
- Serialization: The process of converting the in-memory state of an active Java object into a byte stream, suitable for persisting to disk files or transmission across network sockets.
- Deserialization: The reverse process of reconstructing the live Java object instance in heap memory from the stored byte stream.
SerializableInterface: A marker interface (contains no methods) belonging tojava.io. It signals to the JVM that instances of this class are legally serializable.transientKeyword: Applied to instance variables that should never be serialized (e.g. passwords, encryption keys, credit card numbers, or temporary caching data). During deserialization, transient fields are reset to their default values (nullfor objects,0for numbers).serialVersionUID: A unique 64-bit identifier used during deserialization to verify that the sender and receiver of a serialized object have loaded classes that are binary-compatible.
2. Complete Serialization & Deserialization Program:
import java.io.*;
// Serializable Class
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int empId;
private String empName;
private double salary;
// Transient field: Will NOT be saved to disk for security reasons
private transient String confidentialPin;
public Employee(int id, String name, double salary, String pin) {
this.empId = id;
this.empName = name;
this.salary = salary;
this.confidentialPin = pin;
}
public void display() {
System.out.println("ID: " + empId + " | Name: " + empName +
" | Salary: ₹" + salary + " | PIN: " + confidentialPin);
}
}
public class SerializationMasterDemo {
public static void main(String[] args) {
String filename = "employee_record.ser";
// 1. Serialization: Writing Object to File
Employee emp1 = new Employee(501, "Amitabh Sharma", 75000.0, "SECURE_PIN_987");
System.out.println("Original Object Before Serialization:");
emp1.display();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(emp1);
System.out.println("-> Object successfully serialized to disk file: " + filename);
} catch (IOException e) {
System.err.println("Serialization Error: " + e.getMessage());
}
System.out.println("--------------------------------------------------");
// 2. Deserialization: Restoring Object from File
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
Employee restoredEmp = (Employee) ois.readObject();
System.out.println("Reconstructed Object After Deserialization:");
restoredEmp.display(); // Notice confidentialPin will be null!
} catch (IOException | ClassNotFoundException e) {
System.err.println("Deserialization Error: " + e.getMessage());
}
}
}
Original Object Before Serialization:ID: 501 | Name: Amitabh Sharma | Salary: ₹75000.0 | PIN: SECURE_PIN_987-> Object successfully serialized to disk file: employee_record.ser--------------------------------------------------Reconstructed Object After Deserialization:ID: 501 | Name: Amitabh Sharma | Salary: ₹75000.0 | PIN: null(Notice that the transient PIN field was safely dropped and initialized to null!)
Q30. Discuss the architecture of the Java Collections Framework. Compare ArrayList, LinkedList, and Vector with Big-O complexity. Demonstrate sorting a custom object list using both Comparable and Comparator interfaces with working code.
1. Collections Framework Architecture & Big-O Complexity Comparison:
| Collection Class | Underlying Data Structure | Random Access Get(i) | Insert / Delete | Thread Safety | Growth Factor |
|---|---|---|---|---|---|
ArrayList |
Dynamic Resizable Array | $O(1)$ fast | $O(N)$ (requires memory shift) | Not Thread-Safe (Fast) | Grows by 50% (1.5x) |
LinkedList |
Doubly Linked List | $O(N)$ sequential traverse | $O(1)$ at node pointer | Not Thread-Safe | No capacity preallocation |
Vector |
Synchronized Dynamic Array | $O(1)$ | $O(N)$ | Thread-Safe (Synchronized, slow) | Grows by 100% (2x) |
2. Sorting with Comparable vs Comparator:
import java.util.*;
// Comparable defines Natural Default Ordering (e.g. by Roll Number)
class StudentRecord implements Comparable<StudentRecord> {
int rollNo;
String name;
double cgpa;
public StudentRecord(int rollNo, String name, double cgpa) {
this.rollNo = rollNo;
this.name = name;
this.cgpa = cgpa;
}
@Override
public int compareTo(StudentRecord other) {
return Integer.compare(this.rollNo, other.rollNo); // Ascending roll number
}
@Override
public String toString() {
return String.format("[Roll: %d | Name: %-12s | CGPA: %.2f]", rollNo, name, cgpa);
}
}
// Comparator defines Custom Alternative Ordering (e.g. Descending CGPA)
class CgpaComparator implements Comparator<StudentRecord> {
@Override
public int compare(StudentRecord s1, StudentRecord s2) {
return Double.compare(s2.cgpa, s1.cgpa); // High to low CGPA
}
}
public class CollectionsSortingMasterDemo {
public static void main(String[] args) {
List<StudentRecord> students = new ArrayList<>();
students.add(new StudentRecord(105, "Priya Singh", 8.9));
students.add(new StudentRecord(101, "Rahul Verma", 9.4));
students.add(new StudentRecord(108, "Deepak Joshi", 7.8));
students.add(new StudentRecord(102, "Ananya Roy", 9.1));
System.out.println("1. Natural Sorting by Roll No (Comparable):");
Collections.sort(students);
for (StudentRecord s : students) System.out.println(s);
System.out.println("\n2. Merit Rank Sorting by CGPA Descending (Comparator):");
Collections.sort(students, new CgpaComparator());
for (StudentRecord s : students) System.out.println(s);
}
}
1. Natural Sorting by Roll No (Comparable):[Roll: 101 | Name: Rahul Verma | CGPA: 9.40][Roll: 102 | Name: Ananya Roy | CGPA: 9.10][Roll: 105 | Name: Priya Singh | CGPA: 8.90][Roll: 108 | Name: Deepak Joshi | CGPA: 7.80]2. Merit Rank Sorting by CGPA Descending (Comparator):[Roll: 101 | Name: Rahul Verma | CGPA: 9.40][Roll: 102 | Name: Ananya Roy | CGPA: 9.10][Roll: 105 | Name: Priya Singh | CGPA: 8.90][Roll: 108 | Name: Deepak Joshi | CGPA: 7.80]