0% found this document useful (0 votes)
1 views33 pages

Java Programming BCA QA

Some questions and of java programming language

Uploaded by

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

Java Programming BCA QA

Some questions and of java programming language

Uploaded by

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

Prof.

Rajendra Singh (Rajju Bhaiya) University, Prayagraj


Bachelor of Computer Applications (BCA)
Java Programming – Comprehensive Question Bank

Marks Guide: Short Answer = 3 Marks | Long Answer = 7 Marks | Very Long Answer = 15 Marks

UNIT I – Introduction to Java & OOP Basics

SHORT ANSWER QUESTIONS (3 Marks)

Q1. What is Java? List its main features.


Java is a high-level, object-oriented, platform-independent programming language developed by Sun
Microsystems (1995). Main features: (1) Platform Independence – Write Once Run Anywhere via JVM; (2)
Object-Oriented – supports classes, objects, inheritance, polymorphism; (3) Robust – strong memory
management, exception handling; (4) Secure – no pointers, bytecode verification; (5) Multithreaded –
built-in thread support; (6) Simple – clean syntax based on C/C++.

Q2. Differentiate between JDK, JRE, and JVM.


JVM (Java Virtual Machine): Executes Java bytecode; platform-specific. JRE (Java Runtime Environment):
JVM + class libraries; used to run Java programs. JDK (Java Development Kit): JRE + compiler (javac) +
development tools; used to develop Java programs. Hierarchy: JDK ⊇ JRE ⊇ JVM.

Q3. What are Java data types? Give examples.


Java has two categories: (1) Primitive – byte, short, int, long, float, double, char, boolean. Example: int
x=10; double pi=3.14; char c='A'; boolean flag=true; (2) Non-Primitive (Reference) – String, Array, Class,
Interface. Example: String name="Java";

Q4. What are operators in Java? List the types.


Operators perform operations on variables/values. Types: (1) Arithmetic: +, -, *, /, % (2) Relational: ==, !=,
>, <, >=, <= (3) Logical: &&, ||, ! (4) Assignment: =, +=, -= (5) Bitwise: &, |, ^, ~, <<, >> (6) Unary: ++, -- (7)
Ternary: condition ? true : false

Q5. What is the difference between = and == in Java?


= is the assignment operator; it assigns a value to a variable. Example: int a = 5; stores 5 in a. == is the
equality/comparison operator; it checks whether two values are equal and returns boolean. Example: if(a
== 5) returns true. Using = inside a condition is a common programming error.

Q6. What is a variable in Java? How is it declared?


A variable is a named memory location that stores data. Syntax: datatype variableName = value; Types: (1)
Local – declared inside method, (2) Instance – declared inside class but outside method, (3) Static –
declared with static keyword. Example: int age = 20; (local), static int count = 0; (static).

Q7. What are control structures? Name them.


Control structures determine the flow of program execution. Types: (1) Selection/Decision: if, if-else,
if-else-if ladder, switch-case. (2) Looping/Iteration: for, while, do-while, enhanced for-each. (3) Jump: break,
continue, return. They allow the programmer to control which statements execute and how many times.

Q8. What is a constructor in Java?


A constructor is a special method used to initialize objects. Rules: (1) Same name as class, (2) No return
type. Types: (1) Default constructor – no parameters, auto-provided by Java. (2) Parameterized constructor
– takes arguments. Example: class Car { String name; Car(String n){ name=n; } } — called as: Car c = new
Car("BMW");

Q9. What is method overloading?


Method overloading means defining multiple methods in the same class with the same name but different
parameter lists (type, number, or order). It is a form of compile-time (static) polymorphism. Example: int
add(int a, int b), double add(double a, double b) — both are valid in the same class. Return type alone does
not distinguish overloaded methods.

Q10. What is the Math class in Java?


The Math class in [Link] package provides static methods for mathematical operations. No need to
create an object. Common methods: [Link](x) – absolute value, [Link](x) – square root,
[Link](x,y) – x to power y, [Link](a,b) – maximum, [Link](a,b) – minimum, [Link](x) – rounds
up, [Link](x) – rounds down, [Link]() – random number 0.0–1.0.

Q11. What is the 'this' keyword in Java?


this refers to the current object of the class. Uses: (1) Distinguish instance variables from local variables
with same name: [Link] = name; (2) Call another constructor in same class: this(); (3) Pass current
object as argument: display(this); (4) Return current object from a method: return this; It cannot be used in
static methods.

Q12. What is a Finalizer in Java?


The finalize() method is called by the garbage collector before destroying an object, allowing cleanup of
resources (closing files, releasing connections). Syntax: protected void finalize(){ // cleanup code } It is
defined in the Object class. Note: It is deprecated in Java 9+ and not reliable for resource management;
try-with-resources is preferred.

LONG ANSWER QUESTIONS (7 Marks)

Q1. Explain all types of control structures in Java with syntax and examples.
Control structures control program execution flow.

1. if-else: if(condition){ stmts } else{ stmts } — Executes block based on condition.


2. if-else-if ladder: Checks multiple conditions in sequence.
3. switch-case: switch(var){ case 1: ...; break; default: ...; } — Used for multi-way branching.
4. for loop: for(init; condition; update){ } — Used when number of iterations is known.
5. while loop: while(condition){ } — Checks condition before executing.
6. do-while: do{ }while(condition); — Executes at least once, checks condition after.
7. for-each: for(type var : array){ } — Iterates over arrays/collections.
8. break: Exits current loop or switch immediately.
9. continue: Skips current iteration and moves to next.
10. return: Exits method, optionally returning a value.

Example — Factorial using for loop: int fact=1; for(int i=1;i<=n;i++) fact*=i;
Example — switch: switch(day){ case 1: [Link]("Monday"); break; }
Control structures are the backbone of any algorithm implementation in Java.

Q2. Explain Arrays in Java with declaration, types, and examples.


An array is a collection of elements of the same type stored in contiguous memory.

Declaration & Initialization:


int[] arr = new int[5]; // Default values: 0
int[] arr = {10, 20, 30, 40, 50}; // Direct initialization

Types:
1. Single-dimensional: int[] a = {1,2,3};
Access: a[0]=1, a[1]=2 ... Index starts from 0.

2. Multi-dimensional: int[][] matrix = new int[3][3];


int[][] m = {{1,2},{3,4}}; 2D array / matrix.

3. Jagged Array: Array of arrays with different lengths.


int[][] jag = new int[3][]; jag[0]=new int[2]; jag[1]=new int[4];

Important properties:
- length attribute: [Link] gives size.
- Passed by reference to methods.
- [Link] class provides sorting, searching: [Link](arr);

Example program — sum of array:


int[] nums = {5,10,15,20};
int sum=0;
for(int x : nums) sum += x;
[Link]("Sum = " + sum); // Output: Sum = 50

Q3. Explain classes and objects in Java with a complete example.


A class is a blueprint/template that defines attributes (fields) and behaviors (methods). An object is an
instance of a class created in heap memory.

Syntax:
class ClassName {
// Fields (attributes)
datatype fieldName;
// Constructor
ClassName(params){ ... }
// Methods
returnType methodName(params){ ... }
}

Object Creation: ClassName obj = new ClassName(args);

Example — Student class:


class Student {
int rollNo;
String name;
float marks;

Student(int r, String n, float m){


rollNo=r; name=n; marks=m;
}

void display(){
[Link](rollNo + " " + name + " " + marks);
}
}

class Main {
public static void main(String[] args){
Student s1 = new Student(101, "Rahul", 88.5f);
Student s2 = new Student(102, "Priya", 92.0f);
[Link]();
[Link]();
}
}

Key concepts:
- new keyword allocates memory and calls constructor.
- Each object has its own copy of instance variables.
- Methods are shared among all objects.
- null is the default value of an uninitialized reference.

Q4. Explain String, StringBuffer, and Character classes in Java.


1. String Class ([Link]):
- Immutable (cannot be changed once created).
- String s = "Hello"; or String s = new String("Hello");
- Key methods: length(), charAt(i), substring(i,j), indexOf(ch), toUpperCase(), toLowerCase(), equals(),
trim(), replace(), concat(), split(), contains().
- String concatenation: + operator, creates new String object each time.

2. StringBuffer Class:
- Mutable (can be modified without creating new objects).
- Thread-safe (synchronized). Preferred for modification-heavy operations.
- StringBuffer sb = new StringBuffer("Hello");
- Key methods: append("World"), insert(i,"str"), delete(i,j), reverse(), replace(i,j,"str"), length(), charAt(i).
- StringBuilder: Similar to StringBuffer but NOT thread-safe, faster for single-thread use.

3. Character Class ([Link]):


- Wrapper for primitive char.
- Useful static methods: [Link](c), isLetter(c), isUpperCase(c), isLowerCase(c), isWhitespace(c),
toUpperCase(c), toLowerCase(c), isAlphabetic(c).

Comparison:
| Feature | String | StringBuffer | StringBuilder |
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes | Yes | No |
| Performance | Slow (concat)| Moderate | Fast |

VERY LONG ANSWER QUESTIONS (15 Marks)


Q1. Write a detailed note on Object-Oriented Programming in Java. Explain all OOPS principles
with examples.
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around
data (objects) rather than functions and logic. Java is a fully object-oriented language (except primitive
types).

■■■ FOUR PILLARS OF OOP ■■■

1. ENCAPSULATION
Definition: Wrapping data (fields) and methods into a single unit (class) and restricting direct access using
access modifiers.
Implementation: Use private fields + public getters/setters.
Example:
class BankAccount {
private double balance;
public void deposit(double amt){ if(amt>0) balance += amt; }
public double getBalance(){ return balance; }
}
Benefits: Data hiding, controlled access, easy maintenance.

2. INHERITANCE
Definition: One class (child/subclass) acquires properties of another class (parent/superclass) using
extends keyword.
Types: Single, Multilevel, Hierarchical (Multiple via interfaces).
Example:
class Animal { void sound(){ [Link]("Sound"); } }
class Dog extends Animal { void sound(){ [Link]("Bark"); } }
super keyword: accesses parent class members.
Benefits: Code reusability, IS-A relationship.

3. POLYMORPHISM
Definition: "Many forms" — same action behaving differently in different contexts.

a) Compile-time (Static) Polymorphism — Method Overloading:


Same method name, different parameters in same class.
int add(int a,int b){ return a+b; }
double add(double a,double b){ return a+b; }

b) Runtime (Dynamic) Polymorphism — Method Overriding:


Child class redefines parent method. JVM decides at runtime.
class Shape { void draw(){ } }
class Circle extends Shape { void draw(){ [Link]("Circle"); } }
Shape s = new Circle(); [Link](); // prints Circle

4. ABSTRACTION
Definition: Hiding implementation details; showing only essential features.

a) Abstract Class: declared with abstract keyword; can have abstract + concrete methods.
abstract class Vehicle { abstract void start(); void stop(){...} }

b) Interface: 100% abstraction; all methods are abstract (default in Java 7).
interface Flyable { void fly(); }
class Bird implements Flyable { public void fly(){...} }

■■■ OTHER OOP CONCEPTS ■■■

5. CLASS & OBJECT: Class = blueprint; Object = instance. Created with new keyword.

6. CONSTRUCTOR: Special method to initialize object. Default or parameterized.

7. ACCESS MODIFIERS:
- private: same class only
- default: same package
- protected: same package + subclasses
- public: everywhere

8. STATIC MEMBERS: Belong to class, not object. Shared among all instances.
static int count = 0; called as [Link];

9. FINAL KEYWORD:
- final variable: constant (cannot change).
- final method: cannot be overridden.
- final class: cannot be inherited.

10. METHOD OVERLOADING vs OVERRIDING:


| Feature | Overloading | Overriding |
| Location | Same class | Different classes |
| Params | Must differ | Must be same |
| Binding | Compile-time | Runtime |
| Return type | Can differ | Must be same/covariant |

Java achieves OOP through its class hierarchy rooted at [Link], which is the parent of all Java
classes, providing common methods like toString(), equals(), hashCode(), and clone().

Java is said to be "not 100% OOP" because it still uses primitive data types (int, float, etc.) which are not
objects. However, wrapper classes (Integer, Float, etc.) bridge this gap through autoboxing/unboxing.

Q2. Write complete Java programs demonstrating: (a) Method Overloading (b) Constructor
Overloading (c) Use of 'this' keyword (d) String operations (e) Arrays.
(a) METHOD OVERLOADING:
class Calculator {
int add(int a, int b){ return a+b; }
double add(double a, double b){ return a+b; }
int add(int a, int b, int c){ return a+b+c; }
String add(String s1, String s2){ return s1+s2; }

public static void main(String[] args){


Calculator c = new Calculator();
[Link]([Link](3,4)); // 7
[Link]([Link](2.5, 3.5)); // 6.0
[Link]([Link](1,2,3)); // 6
[Link]([Link]("Hello","World")); // HelloWorld
}
}

(b) CONSTRUCTOR OVERLOADING:


class Employee {
String name; int age; double salary;

Employee(){ name="Unknown"; age=0; salary=0; }


Employee(String n){ name=n; }
Employee(String n, int a){ name=n; age=a; }
Employee(String n, int a, double s){ name=n; age=a; salary=s; }

void show(){
[Link](name+" | Age:"+age+" | Salary:"+salary);
}
public static void main(String[] args){
Employee e1 = new Employee();
Employee e2 = new Employee("Amit", 25, 50000);
[Link](); [Link]();
}
}

(c) THIS KEYWORD:


class Student {
String name; int rollNo;

Student(String name, int rollNo){


[Link] = name; // resolve ambiguity
[Link] = rollNo;
}
Student(){ this("Default", 0); } // call another constructor

Student getSelf(){ return this; } // return current object

void display(){ [Link](rollNo+": "+name); }


}

(d) STRING OPERATIONS:


public class StringDemo {
public static void main(String[] args){
String s = " Hello Java World ";
[Link]([Link]()); // Hello Java World
[Link]([Link]().toUpperCase()); // HELLO JAVA WORLD
[Link]([Link]().length()); // 16
[Link]([Link]("Java")); // true
[Link]([Link]("Java","Python")); // Hello Python World
[Link]([Link](7,11)); // Java
String[] words = [Link]().split(" ");
for(String w : words) [Link](w);
StringBuffer sb = new StringBuffer("Hello");
[Link](" World").insert(5,",").reverse();
[Link](sb); // dlroW ,olleH
}
}

(e) ARRAYS:
public class ArrayDemo {
public static void main(String[] args){
// 1D Array
int[] marks = {85, 92, 78, 95, 88};
int sum=0, max=marks[0];
for(int m : marks){ sum+=m; if(m>max) max=m; }
[Link]("Avg: "+(sum/[Link])+", Max: "+max);

// 2D Array (Matrix multiplication)


int[][] a = {{1,2},{3,4}};
int[][] b = {{5,6},{7,8}};
int[][] c = new int[2][2];
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
c[i][j] += a[i][k]*b[k][j];
[Link](c[0][0]+" "+c[0][1]);
[Link](c[1][0]+" "+c[1][1]);
// Output: 19 22 / 43 50
}
}
UNIT II – Inheritance, Polymorphism & Advanced OOP

SHORT ANSWER QUESTIONS (3 Marks)

Q1. What is inheritance? What are its types?


Inheritance allows a subclass to inherit fields and methods of a superclass using extends. Types: (1) Single
– one parent, one child. (2) Multilevel – A→B→C chain. (3) Hierarchical – one parent, multiple children. (4)
Multiple – achieved via interfaces (not classes). (5) Hybrid – combination. Benefits: code reusability,
method overriding, IS-A relationship.

Q2. What is the difference between super and this?


this refers to the current class object; super refers to the immediate parent class. this() calls current class
constructor; super() calls parent constructor. [Link] accesses current class field; [Link] accesses
parent class field. [Link]() calls overridden parent method. super() must be the first statement in
constructor if used.

Q3. What is method overriding?


When a subclass provides its own implementation of a method already defined in the parent class with the
same name, return type, and parameters. Enables runtime polymorphism. Rules: (1) Method signature
must match, (2) Access modifier cannot be more restrictive, (3) Cannot override static/final/private
methods, (4) Use @Override annotation for safety.

Q4. What is an abstract class?


A class declared with the abstract keyword that may contain abstract methods (no body) and concrete
methods. Cannot be instantiated directly. Subclasses must implement all abstract methods (or be abstract
themselves). Syntax: abstract class Shape{ abstract void draw(); void display(){...} } Used when some
functionality is common and some must be implemented by subclasses.

Q5. What is an Interface in Java?


An interface is a 100% abstract type (in Java 7) that specifies what a class must do but not how. Contains:
abstract methods (public abstract by default), constants (public static final). A class implements an interface
with implements keyword. A class can implement multiple interfaces (solving multiple inheritance). Java 8+
allows default and static methods in interfaces.

Q6. What is dynamic binding?


Dynamic binding (late binding) is the process where the method to be called is determined at runtime, not
compile time. It occurs with method overriding. Example: Shape s = new Circle(); [Link](); — Java
determines at runtime that Circle's draw() should be called based on the actual object type, not the
reference type. It is the mechanism behind runtime polymorphism.

Q7. What is casting in Java?


Casting converts one type to another. (1) Widening (Implicit): smaller to larger type, automatic. int → long
→ float → double. (2) Narrowing (Explicit): larger to smaller, manual, may lose data. double d=9.8; int
i=(int)d; // i=9. (3) Object casting: Upcasting (Child→Parent, implicit), Downcasting (Parent→Child, explicit).
Use instanceof before downcasting to avoid ClassCastException.

Q8. What is the instanceof operator?


instanceof is a binary operator that checks whether an object is an instance of a specified class or interface.
Returns boolean. Syntax: objectRef instanceof ClassName. Example: if(animal instanceof Dog){ Dog
d=(Dog)animal; [Link](); } Used before downcasting to prevent ClassCastException. Also true if the object
is a subclass instance of the given type.

Q9. What is a Package in Java?


A package is a namespace that organizes related classes and interfaces into groups, avoiding name
conflicts. Types: (1) Built-in: [Link] (auto-imported), [Link], [Link], [Link], [Link]. (2)
User-defined: package mypack; at top of file. Import: import [Link]; or import [Link].*; Benefits:
modularity, access protection, reusability.

Q10. What is the UTIL package?


[Link] is a built-in package providing utility classes. Key classes/interfaces: ArrayList, LinkedList,
HashMap, HashSet, TreeMap, Stack, Queue (Collections Framework); Scanner (user input); Date,
Calendar (date handling); Arrays (array operations); Math (math functions); Random (random numbers);
Iterator (traversal). It is one of the most widely used packages in Java development.

Q11. What is Generic Programming in Java?


Generics allow classes, interfaces, and methods to operate on parameterized types, providing type safety
and eliminating type casting. Syntax: class Box{ T value; } Used as: Box b = new Box<>();. Benefits:
compile-time type checking, no ClassCastException, code reusability. The Collections Framework heavily
uses generics. Example: ArrayList list = new ArrayList<>();

Q12. What is the Object class?


[Link] is the root of the Java class hierarchy — every class implicitly extends Object. It provides
universal methods: toString() (string representation), equals(obj) (equality check), hashCode() (hash value),
clone() (object copy), getClass() (runtime class info), finalize() (pre-GC cleanup), wait(), notify(), notifyAll()
(thread synchronization). Overriding toString() and equals() is a common practice.

LONG ANSWER QUESTIONS (7 Marks)

Q1. Explain all types of inheritance in Java with examples and diagrams.
Inheritance = acquiring properties and behaviors of parent class using extends.

1. SINGLE INHERITANCE:
class Animal{ void eat(){...} }
class Dog extends Animal{ void bark(){...} }
→ Dog inherits eat() from Animal. Simple parent-child.

2. MULTILEVEL INHERITANCE:
class Animal{ void breathe(){...} }
class Mammal extends Animal{ void feed(){...} }
class Dog extends Mammal{ void bark(){...} }
→ Dog inherits from Mammal which inherits from Animal. Chain.

3. HIERARCHICAL INHERITANCE:
class Shape{ void draw(){...} }
class Circle extends Shape{ void draw(){[Link]("Circle");} }
class Square extends Shape{ void draw(){[Link]("Square");} }
→ Multiple children from one parent.

4. MULTIPLE INHERITANCE (via Interfaces):


Java does NOT support multiple class inheritance (Diamond problem).
But it allows multiple interface implementation:
interface Flyable{ void fly(); }
interface Swimmable{ void swim(); }
class Duck implements Flyable, Swimmable{
public void fly(){ [Link]("Duck flies"); }
public void swim(){ [Link]("Duck swims"); }
}

5. HYBRID INHERITANCE: Combination of above types, only through interfaces.

super keyword usage:


- super() calls parent constructor (must be first statement).
- [Link]() calls parent version of overridden method.
- [Link] accesses parent field hidden by child.

Benefits: code reuse, extensibility, polymorphism support, IS-A relationship.


Limitation: increases coupling between classes; deep hierarchies are hard to maintain.

Q2. Explain Abstract Class and Interface with differences and examples.
ABSTRACT CLASS:
- Declared with abstract keyword.
- Can have abstract methods (no body) + concrete methods.
- Can have constructors, instance variables, static methods.
- A class can extend only ONE abstract class.
- Cannot instantiate directly.

Example:
abstract class Vehicle {
String brand;
Vehicle(String b){ brand=b; }
abstract void start(); // must be overridden
void displayBrand(){ [Link]("Brand: "+brand); }
}
class Car extends Vehicle {
Car(String b){ super(b); }
public void start(){ [Link](brand+" car starts with key"); }
}

INTERFACE:
- Declared with interface keyword.
- All methods are public abstract by default (Java 7).
- Java 8+: can have default and static methods.
- All variables are public static final (constants).
- A class can implement MULTIPLE interfaces.
- Cannot have constructors or instance variables.

Example:
interface Printable{ void print(); }
interface Saveable{ void save(); }
class Document implements Printable, Saveable {
public void print(){ [Link]("Printing..."); }
public void save(){ [Link]("Saving..."); }
}

KEY DIFFERENCES:
| Feature | Abstract Class | Interface |
| Keyword | abstract | interface |
| Methods | Abstract + Concrete | Abstract (default/static Java8+) |
| Variables | Any type | public static final |
| Constructors | Yes | No |
| Inheritance | Single (extends) | Multiple (implements) |
| Access modifiers | Any | public only |
| When to use | Partial implementation | Full contract/multiple inheritance |

Q3. What is Polymorphism? Explain compile-time and runtime polymorphism with examples.
Polymorphism means "many forms." The same method name behaves differently based on context.

TYPE 1 — COMPILE-TIME POLYMORPHISM (Method Overloading):


Resolved by compiler. Same method name, different parameter list in same class.

class MathOps {
int square(int x){ return x*x; }
double square(double x){ return x*x; }
long square(long x){ return x*x; }
}
MathOps m = new MathOps();
[Link](5); // calls int version
[Link](3.14); // calls double version

Rules: Parameters must differ in type, number, or order. Return type alone cannot distinguish.

TYPE 2 — RUNTIME POLYMORPHISM (Method Overriding + Dynamic Dispatch):


Resolved at runtime. Child redefines parent's method. Parent reference holds child object.

class Shape { void area(){ [Link]("Shape area"); } }


class Circle extends Shape {
void area(){ [Link]("pi*r*r"); }
}
class Rectangle extends Shape {
void area(){ [Link]("l*b"); }
}

Shape s;
s = new Circle(); [Link](); // pi*r*r (runtime decision)
s = new Rectangle(); [Link](); // l*b (runtime decision)

Dynamic Method Dispatch: JVM looks at actual object type (not reference type) at runtime.

Conditions for runtime polymorphism:


1. Inheritance must exist.
2. Method must be overridden.
3. Parent reference must point to child object.

@Override annotation: ensures method is actually overriding; compiler gives error if not.

VERY LONG ANSWER QUESTIONS (15 Marks)

Q1. Write a comprehensive Java program demonstrating Inheritance, Polymorphism, Abstract


Class, and Interface together (Banking System example).
// INTERFACE
interface Transactional {
void deposit(double amount);
void withdraw(double amount);
default void showStatement(){ [Link]("Statement available"); }
}

interface Printable {
void printDetails();
}

// ABSTRACT CLASS
abstract class BankAccount implements Transactional, Printable {
protected String accountNo;
protected String holderName;
protected double balance;
protected String accountType;

BankAccount(String accNo, String name, double bal) {


[Link] = accNo;
[Link] = name;
[Link] = bal;
}

// Concrete method
public void deposit(double amount){
if(amount > 0){ balance += amount; [Link]("Deposited: "+amount); }
}

// Abstract method — each account type implements differently


abstract double calculateInterest();
abstract String getAccountType();
}

// SAVINGS ACCOUNT (Single Inheritance from BankAccount)


class SavingsAccount extends BankAccount {
private double interestRate = 0.04; // 4%

SavingsAccount(String accNo, String name, double bal){


super(accNo, name, bal);
}
public void withdraw(double amount){
if(amount > 0 && balance - amount >= 1000) // min balance
{ balance -= amount; [Link]("Withdrawn: "+amount); }
else [Link]("Insufficient balance or below minimum!");
}

public double calculateInterest(){ return balance * interestRate; }


public String getAccountType(){ return "Savings"; }

public void printDetails(){


[Link]("=== Savings Account ===");
[Link]("Acc No: "+accountNo+" | Name: "+holderName);
[Link]("Balance: "+balance+" | Interest: "+calculateInterest());
}
}

// CURRENT ACCOUNT
class CurrentAccount extends BankAccount {
private double overdraftLimit = 10000;

CurrentAccount(String accNo, String name, double bal){


super(accNo, name, bal);
}

public void withdraw(double amount){


if(balance + overdraftLimit >= amount){
balance -= amount;
[Link]("Withdrawn: "+amount+" | Balance: "+balance);
} else [Link]("Overdraft limit exceeded!");
}

public double calculateInterest(){ return balance * 0.02; } // 2%


public String getAccountType(){ return "Current"; }

public void printDetails(){


[Link]("=== Current Account ===");
[Link]("Acc No: "+accountNo+" | Name: "+holderName);
[Link]("Balance: "+balance+" | Overdraft: "+overdraftLimit);
}
}

// MAIN CLASS — Runtime Polymorphism in action


class BankDemo {
public static void main(String[] args){
// Polymorphic array
BankAccount[] accounts = new BankAccount[3];
accounts[0] = new SavingsAccount("SA001","Rahul",50000);
accounts[1] = new CurrentAccount("CA001","Priya",100000);
accounts[2] = new SavingsAccount("SA002","Amit",75000);
for(BankAccount acc : accounts){
[Link](); // Runtime polymorphism
[Link](5000);
[Link](2000);
[Link](); // Default interface method
[Link]("Interest: "+[Link]());
[Link]("Type: "+[Link]());
[Link]("---");
}

// instanceof check
for(BankAccount acc : accounts){
if(acc instanceof SavingsAccount){
[Link]([Link]+" is a Savings Account");
}
}
}
}

// OUTPUT (sample):
// === Savings Account ===
// Acc No: SA001 | Name: Rahul | Balance: 50000.0 | Interest: 2000.0
// Deposited: 5000.0
// Withdrawn: 2000.0
// Statement available
// Interest: 2120.0 (on updated balance)
// Type: Savings

Key Concepts Demonstrated:


1. Abstract class (BankAccount) with abstract + concrete methods.
2. Two Interfaces (Transactional, Printable) with default method.
3. Single Inheritance (Savings/Current extends BankAccount).
4. Method Overriding (withdraw, printDetails, calculateInterest).
5. Runtime Polymorphism (BankAccount[] holds different account types).
6. instanceof operator for type checking.
7. super() for parent constructor call.
8. Encapsulation with private fields and public methods.
UNIT III – GUI, Event Handling, Applets, Swing & I/O

SHORT ANSWER QUESTIONS (3 Marks)

Q1. What is Event Handling in Java?


Event handling is the mechanism to respond to user actions (mouse click, key press, button click).
Components: (1) Event Source – object that generates event (Button, TextField). (2) Event Object – holds
info about event (ActionEvent, MouseEvent). (3) Event Listener – interface that handles event
(ActionListener, MouseListener). (4) Event Handler – method that processes event (actionPerformed,
mouseClicked). Use addActionListener() to register.

Q2. What is the difference between AWT and Swing?


AWT (Abstract Window Toolkit): Platform-dependent (heavyweight), uses OS components, limited
components, package [Link]. Swing: Platform-independent (lightweight), written in pure Java, richer
components (JButton, JTable, JTree), MVC architecture, pluggable look-and-feel, package [Link].
Swing components are prefixed with 'J' (JFrame, JButton, JPanel). Swing is generally preferred for modern
Java GUI applications.

Q3. What are Layout Managers? Name them.


Layout managers automatically arrange components in a container. Types: (1) FlowLayout – left to right,
wraps to next line (default for JPanel). (2) BorderLayout – 5 regions: North, South, East, West, Center
(default for JFrame). (3) GridLayout – equal-sized grid. (4) GridBagLayout – flexible grid with constraints.
(5) BoxLayout – single row or column. (6) CardLayout – stacked cards, one visible at a time.

Q4. What is an Applet? What is its life cycle?


An Applet is a Java program embedded in a web page (deprecated in modern Java). Life cycle methods:
(1) init() – called once on load; initialization code. (2) start() – called after init() and each time page is
revisited. (3) paint(Graphics g) – called to draw/redraw. (4) stop() – called when page is left. (5) destroy() –
called when applet is removed from memory. Order: init → start → paint → stop → destroy.

Q5. What is the difference between Frame and Panel?


Frame (JFrame): Top-level window with title bar, border, menu bar. Can be shown independently. Has
window controls (close, minimize, maximize). Created as: JFrame f = new JFrame('Title'); Panel (JPanel):
Lightweight container without window decoration. Cannot exist independently; must be added to a Frame or
another panel. Used to organize components. Default layout: FlowLayout. Used as: JPanel p = new
JPanel();

Q6. What is exception handling in Java?


Exception handling manages runtime errors gracefully without crashing. Keywords: (1) try – encloses code
that may throw exception. (2) catch – handles specific exception. (3) finally – always executes (cleanup).
(4) throw – manually throw an exception. (5) throws – declare that method may throw exception. Types:
Checked (IOException, SQLException) – must be handled; Unchecked (NullPointerException,
ArrayIndexOutOfBoundsException) – optional. Class hierarchy: Throwable → Error/Exception →
RuntimeException.

Q7. What are the GUI components available in Swing?


Key Swing components: JButton (clickable button), JLabel (text/image display), JTextField (single-line
input), JTextArea (multi-line input), JCheckBox (multiple selection), JRadioButton (single from group in
ButtonGroup), JComboBox (dropdown list), JList (scrollable list), JScrollBar (scroll control), JSlider (range
selector), JMenu/JMenuBar/JMenuItem (menus), JDialog (popup window), JTable (tabular data), JTree
(hierarchical data).

Q8. What is Text I/O in Java?


Text I/O handles reading/writing of character data. Key classes: FileReader/FileWriter – character streams
for files. BufferedReader/BufferedWriter – buffered for efficiency. PrintWriter – convenient write methods.
Scanner – easy reading with nextLine(), nextInt(). Example: BufferedReader br = new BufferedReader(new
FileReader('[Link]')); String line = [Link](); while(line != null){ [Link](line);
line=[Link](); } [Link]();

Q9. What is Binary I/O in Java?


Binary I/O handles reading/writing of raw bytes (images, audio, objects). Key classes:
FileInputStream/FileOutputStream – byte streams for files. BufferedInputStream/BufferedOutputStream –
buffered byte streams. DataInputStream/DataOutputStream – read/write primitive types as bytes.
ObjectInputStream/ObjectOutputStream – object serialization. Example: FileOutputStream fos = new
FileOutputStream('[Link]'); [Link](65); [Link]();

Q10. What is Object I/O (Serialization)?


Serialization converts an object to a byte stream to save to file or send over network. Deserialization
reconstructs the object. Class must implement Serializable interface (marker interface). Use
[Link](obj) to serialize and [Link]() to deserialize.
transient keyword excludes fields from serialization. Example: ObjectOutputStream oos = new
ObjectOutputStream(new FileOutputStream('[Link]')); [Link](student);

Q11. What is Random Access File?


RandomAccessFile allows reading/writing at any position in a file (not sequentially). Supports a file pointer
that can be moved using seek(position). Modes: 'r' (read-only), 'rw' (read-write). Methods: seek(long pos),
getFilePointer(), length(), read(), write(), readInt(), writeInt() etc. Example: RandomAccessFile raf = new
RandomAccessFile('[Link]','rw'); [Link](10); [Link]('Hello'); [Link](); Useful for database-style
file access.

Q12. What is a MouseEvent?


MouseEvent is generated by mouse actions. MouseListener interface methods: mouseClicked(MouseEvent
e) – mouse clicked. mousePressed(e) – button pressed. mouseReleased(e) – button released.
mouseEntered(e) – mouse enters component. mouseExited(e) – mouse leaves component.
MouseMotionListener: mouseDragged(e), mouseMoved(e). Event info: [Link](), [Link]() (coordinates),
[Link]() (which button), [Link]() (single/double click). MouseAdapter class provides empty
implementations.

LONG ANSWER QUESTIONS (7 Marks)

Q1. Write a Java Swing program with a simple calculator using GUI components.
import [Link].*;
import [Link].*;
import [Link].*;

public class Calculator extends JFrame implements ActionListener {


JTextField display;
String operator=""; double num1=0, num2=0;
boolean start=true;
Calculator(){
setTitle("Calculator"); setSize(300,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Display
display = new JTextField("0");
[Link](new Font("Arial",[Link],24));
[Link]([Link]);
[Link](false);
add(display, [Link]);

// Button panel
JPanel panel = new JPanel(new GridLayout(4,4,5,5));
String[] btns = {"7","8","9","/","4","5","6","*",
"1","2","3","-","0",".","=","+"};
for(String b : btns){
JButton btn = new JButton(b);
[Link](new Font("Arial",[Link],18));
[Link](this);
[Link](btn);
}
add(panel, [Link]);

// Clear button
JButton clr = new JButton("Clear");
[Link](e -> { [Link]("0"); start=true; });
add(clr, [Link]);

setVisible(true);
}

public void actionPerformed(ActionEvent e){


String cmd = [Link]();
if([Link]("[0-9\.]")){
if(start){ [Link](cmd); start=false; }
else [Link]([Link]()+cmd);
} else if([Link]("=")){
num2 = [Link]([Link]());
switch(operator){
case "+": [Link](""+(num1+num2)); break;
case "-": [Link](""+(num1-num2)); break;
case "*": [Link](""+(num1*num2)); break;
case "/": [Link](num2!=0 ? ""+(num1/num2) : "Error"); break;
}
start=true;
} else {
num1=[Link]([Link]());
operator=cmd; start=true;
}
}

public static void main(String[] args){


new Calculator();
}
}
// Features: GridLayout buttons, BorderLayout main frame, ActionListener,
// JTextField display, all four arithmetic operations, clear functionality.

Q2. Explain Event Handling mechanisms in Java with MouseEvent and KeyEvent examples.
EVENT HANDLING ARCHITECTURE:
1. Event Source generates an event object.
2. Source notifies registered Listeners.
3. Listener's handler method is called automatically.

MOUSE EVENT EXAMPLE:


import [Link].*; import [Link].*;
class MouseDemo extends JFrame implements MouseListener {
JLabel label;
MouseDemo(){
setSize(400,300); setTitle("Mouse Events");
label = new JLabel("Move/Click mouse here", [Link]);
add(label);
addMouseListener(this); // Register this class as listener
setVisible(true);
}
public void mouseClicked(MouseEvent e){
[Link]("Clicked at ("+[Link]()+","+[Link]()+") Clicks:"+[Link]());
}
public void mousePressed(MouseEvent e){ [Link]("Mouse Pressed"); }
public void mouseReleased(MouseEvent e){ [Link]("Mouse Released"); }
public void mouseEntered(MouseEvent e){ [Link]("Mouse Entered"); }
public void mouseExited(MouseEvent e){ [Link]("Mouse Exited"); }
public static void main(String[] a){ new MouseDemo(); }
}

KEY EVENT EXAMPLE:


class KeyDemo extends JFrame implements KeyListener {
JLabel label;
KeyDemo(){
setSize(400,200); setTitle("Key Events");
label = new JLabel("Press any key", [Link]);
add(label);
addKeyListener(this);
setFocusable(true);
setVisible(true);
}
public void keyTyped(KeyEvent e){
[Link]("Key Typed: " + [Link]());
}
public void keyPressed(KeyEvent e){
[Link]("Key Pressed: " + [Link]([Link]()));
}
public void keyReleased(KeyEvent e){
[Link]("Key Released");
}
public static void main(String[] a){ new KeyDemo(); }
}

ADAPTER CLASSES: When you need only 1-2 methods of a listener with 5+ methods,
use Adapter class instead of implementing the interface (avoids empty methods):
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
[Link]("Clicked!");
}
// No need to implement other 4 methods
});

ANONYMOUS INNER CLASS & LAMBDA (modern approach):


JButton btn = new JButton("Click");
[Link](e -> [Link]("Button clicked!"));

VERY LONG ANSWER QUESTIONS (15 Marks)

Q1. Explain Swing GUI programming with a complete Student Registration Form covering all
major components, layouts, and event handling.
import [Link].*;
import [Link].*;
import [Link].*;

public class StudentForm extends JFrame {


// Components
JTextField tfName, tfEmail, tfPhone;
JPasswordField tfPassword;
JTextArea taAddress;
JComboBox cbCourse, cbYear;
JRadioButton rbMale, rbFemale;
JCheckBox cbJava, cbPython, cbC;
JButton btnSubmit, btnReset;
JLabel lblStatus;

StudentForm(){
setTitle("Student Registration Form");
setSize(550, 650);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10,10));

// ■■ TITLE PANEL ■■
JLabel title = new JLabel("STUDENT REGISTRATION", [Link]);
[Link](new Font("Arial", [Link], 18));
[Link]([Link]);
[Link](true);
[Link](new Color(33,71,133));
[Link]([Link](10,0,10,0));
add(title, [Link]);

// ■■ FORM PANEL ■■
JPanel form = new JPanel(new GridBagLayout());
[Link]([Link](10,20,10,20));
GridBagConstraints gbc = new GridBagConstraints();
[Link] = [Link];
[Link] = new Insets(5,5,5,5);

// Helper lambda to add label+field pair


int row = 0;

// Name
[Link]=0; [Link]=row; [Link]=0.3;
[Link](new JLabel("Full Name:"), gbc);
tfName = new JTextField(20);
[Link]=1; [Link]=0.7;
[Link](tfName, gbc);

// Email
row++; [Link]=0; [Link]=row;
[Link](new JLabel("Email:"), gbc);
tfEmail = new JTextField(20);
[Link]=1; [Link](tfEmail, gbc);

// Phone
row++; [Link]=0; [Link]=row;
[Link](new JLabel("Phone:"), gbc);
tfPhone = new JTextField(20);
[Link]=1; [Link](tfPhone, gbc);

// Password
row++; [Link]=0; [Link]=row;
[Link](new JLabel("Password:"), gbc);
tfPassword = new JPasswordField(20);
[Link]=1; [Link](tfPassword, gbc);

// Course (JComboBox)
row++; [Link]=0; [Link]=row;
[Link](new JLabel("Course:"), gbc);
cbCourse = new JComboBox<>(new String[]{"BCA","MCA","[Link] CS","[Link]"});
[Link]=1; [Link](cbCourse, gbc);

// Year
row++; [Link]=0; [Link]=row;
[Link](new JLabel("Year:"), gbc);
cbYear = new JComboBox<>(new String[]{"1st Year","2nd Year","3rd Year"});
[Link]=1; [Link](cbYear, gbc);

// Gender (JRadioButton in ButtonGroup)


row++; [Link]=0; [Link]=row;
[Link](new JLabel("Gender:"), gbc);
JPanel gPanel = new JPanel(new FlowLayout([Link]));
rbMale = new JRadioButton("Male"); rbFemale = new JRadioButton("Female");
ButtonGroup bg = new ButtonGroup();
[Link](rbMale); [Link](rbFemale); [Link](true);
[Link](rbMale); [Link](rbFemale);
[Link]=1; [Link](gPanel, gbc);

// Skills (JCheckBox)
row++; [Link]=0; [Link]=row;
[Link](new JLabel("Skills:"), gbc);
JPanel sPanel = new JPanel(new FlowLayout([Link]));
cbJava=new JCheckBox("Java"); cbPython=new JCheckBox("Python");
cbC=new JCheckBox("C/C++");
[Link](cbJava); [Link](cbPython); [Link](cbC);
[Link]=1; [Link](sPanel, gbc);

// Address (JTextArea in JScrollPane)


row++; [Link]=0; [Link]=row;
[Link](new JLabel("Address:"), gbc);
taAddress = new JTextArea(3, 20);
[Link](true);
JScrollPane sp = new JScrollPane(taAddress);
[Link]=1; [Link](sp, gbc);

add(form, [Link]);

// ■■ BUTTON PANEL ■■
JPanel btnPanel = new JPanel(new FlowLayout());
btnSubmit = new JButton("Submit"); btnReset = new JButton("Reset");
[Link](new Color(33,71,133));
[Link]([Link]);
lblStatus = new JLabel("");
[Link]([Link]);
[Link](btnSubmit); [Link](btnReset); [Link](lblStatus);
add(btnPanel, [Link]);

// ■■ EVENT HANDLING ■■
[Link](e -> {
String name=[Link]().trim();
String email=[Link]().trim();
if([Link]()||[Link]()){
[Link]("Name and Email are required!");
[Link]([Link]);
} else {
String skills = ([Link]()?"Java ":"") +
([Link]()?"Python ":"") +
([Link]()?"C/C++ ":"");
String gender = [Link]() ? "Male" : "Female";
[Link](this,
"Name: "+name+"\nEmail: "+email+
"\nCourse: "+[Link]()+
"\nYear: "+[Link]()+
"\nGender: "+gender+"\nSkills: "+skills,
"Registration Successful", JOptionPane.INFORMATION_MESSAGE);
[Link]("Registered successfully!");
[Link](new Color(0,100,0));
}
});

[Link](e -> {
[Link](""); [Link]("");
[Link](""); [Link]("");
[Link](""); [Link](0);
[Link](0); [Link](true);
[Link](false); [Link](false);
[Link](false); [Link]("");
});

setVisible(true);
}

public static void main(String[] args){


[Link](() -> new StudentForm());
}
}
// Demonstrates: JFrame, JPanel, GridBagLayout, BorderLayout, FlowLayout,
// JTextField, JPasswordField, JTextArea, JComboBox, JRadioButton, ButtonGroup,
// JCheckBox, JButton, JLabel, JScrollPane, JOptionPane,
// ActionListener (lambda), Color, Font, BorderFactory.
UNIT IV – Multithreading, Collections, Java Beans & Networking

SHORT ANSWER QUESTIONS (3 Marks)

Q1. What is multithreading in Java?


Multithreading allows concurrent execution of two or more threads within a program. Each thread has its
own call stack but shares heap memory. Benefits: (1) Better CPU utilization, (2) Improved performance for
I/O-bound tasks, (3) Responsive UIs (background tasks), (4) Parallel processing. Java supports
multithreading natively via Thread class and Runnable interface. JVM scheduler determines thread
execution order.

Q2. What is the Thread life cycle?


A thread passes through these states: (1) New – created but not started (Thread t = new Thread()). (2)
Runnable – start() called, ready to run, waiting for CPU. (3) Running – currently executing. (4)
Blocked/Waiting – waiting for resource, lock, or another thread (sleep(), wait(), join()). (5) Timed Waiting –
waiting for specified time (sleep(ms), wait(ms)). (6) Terminated/Dead – run() method completed or
exception thrown. Transitions are managed by JVM scheduler.

Q3. What is the Runnable interface?


Runnable is a functional interface in [Link] with a single method run(). Used to define a thread's task
separately from Thread class. Implementation: class MyTask implements Runnable{ public void run(){ //
task } } Then: Thread t = new Thread(new MyTask()); [Link](); Advantage over extending Thread: class can
still extend another class (Java single inheritance). Also used with lambda: Thread t = new Thread(() ->
[Link]('Running'));

Q4. What is Thread synchronization?


When multiple threads access shared resources concurrently, data inconsistency (race condition) can
occur. Synchronization ensures only one thread accesses a critical section at a time using locks/monitors.
Methods: (1) synchronized method: synchronized void method(){...} — locks the object. (2) synchronized
block: synchronized(obj){...} — finer control. Ensures mutual exclusion. Prevents race conditions,
deadlocks, and inconsistent data. Uses intrinsic lock (monitor) of each object.

Q5. What is Exception Handling with try-catch-finally?


try: encloses code that may throw exception. catch(ExceptionType e): handles specific exception; multiple
catch blocks allowed. finally: always executes regardless of exception (used for cleanup: close
files/connections). throw: manually throw exception. throws: declare in method signature for checked
exceptions. Multi-catch: catch(IOException | SQLException e). try-with-resources: auto-closes resources.
Best practice: catch specific exceptions, not just Exception.

Q6. What is the Collections Framework?


Java Collections Framework (JCF) provides a unified architecture for storing and manipulating groups of
objects. Key interfaces: Collection → List (ArrayList, LinkedList, Vector), Set (HashSet, TreeSet), Queue
(LinkedList, PriorityQueue); Map (HashMap, TreeMap, LinkedHashMap). Utility classes: Collections
(sorting, searching), Arrays. Benefits: reduces programming effort, increases performance, provides
interoperability, promotes software reuse.

Q7. Difference between ArrayList and LinkedList.


ArrayList: backed by dynamic array, fast random access O(1), slow insert/delete in middle O(n), less
memory. LinkedList: doubly linked list, slow random access O(n), fast insert/delete at ends O(1), more
memory (node pointers). Both implement List interface. Use ArrayList for frequent access; LinkedList for
frequent insert/delete. LinkedList also implements Deque, so it can be used as a stack or queue.

Q8. What is HashMap?


HashMap stores key-value pairs. Keys are unique; values can repeat. Based on hashing (uses hashCode()
and equals()). Allows one null key and multiple null values. Not ordered. Not thread-safe (use
ConcurrentHashMap for thread safety). Key methods: put(k,v), get(k), remove(k), containsKey(k),
containsValue(v), keySet(), values(), entrySet(), size(), isEmpty(). Example: HashMap map = new
HashMap<>(); [Link]('Alice',90);

Q9. What are Java Beans?


Java Beans are reusable software components following specific conventions: (1) Public no-arg
constructor, (2) Private fields (encapsulation), (3) Public getters and setters (getXxx/setXxx/isXxx for
boolean), (4) Implements Serializable. Used in JSP/JSF for data binding, IDEs, frameworks (Spring).
Example: class PersonBean implements Serializable{ private String name; public String getName(){return
name;} public void setName(String n){name=n;} }

Q10. What is Network Programming in Java?


Java provides [Link] package for network programming. Key classes: InetAddress – IP address
representation. Socket – client-side TCP connection. ServerSocket – server-side TCP listener.
URL/URLConnection – HTTP connections. DatagramSocket/DatagramPacket – UDP communication.
Basic TCP flow: Server: ServerSocket ss=new ServerSocket(port); Socket s=[Link](); Client: Socket
s=new Socket(host,port); Then use InputStream/OutputStream for data exchange.

Q11. What is the difference between sleep() and wait()?


sleep(): [Link](ms) — pauses current thread for specified ms; does NOT release lock; used for time
delays; can be called from any context. wait(): [Link]() — called on an object; releases the object's lock;
thread waits until notify()/notifyAll() is called; must be called inside synchronized block; throws
InterruptedException. Use sleep() for delays; wait() for inter-thread communication / producer-consumer
pattern.

Q12. What are HashSet and TreeSet?


HashSet: unordered collection of unique elements; backed by HashMap; allows one null; O(1) for
add/remove/contains. TreeSet: sorted (natural order or Comparator) collection of unique elements; backed
by TreeMap; no null allowed; O(log n) operations; implements NavigableSet. Both implement Set interface
(no duplicates). Use HashSet for fast unordered operations; TreeSet when sorted order is needed.

LONG ANSWER QUESTIONS (7 Marks)

Q1. Explain Thread creation in Java with both methods and demonstrate thread synchronization.
METHOD 1 — EXTENDING Thread CLASS:
class CounterThread extends Thread {
String name; int limit;
CounterThread(String n, int l){ name=n; limit=l; }
public void run(){
for(int i=1; i<=limit; i++){
[Link](name + " -> " + i);
try{ [Link](500); } catch(InterruptedException e){ }
}
}
}
METHOD 2 — IMPLEMENTING Runnable INTERFACE:
class PrintTask implements Runnable {
String message; int count;
PrintTask(String m, int c){ message=m; count=c; }
public void run(){
for(int i=0; i [Link]([Link]().getName()+": "+message);
try{ [Link](300); } catch(InterruptedException e){ }
}
}
}

CREATING & RUNNING THREADS:


public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
// Method 1
CounterThread t1 = new CounterThread("Thread-A", 5);
CounterThread t2 = new CounterThread("Thread-B", 5);
[Link](); [Link]();
[Link](); [Link](); // wait for both to finish

// Method 2
Thread t3 = new Thread(new PrintTask("Hello",3), "Worker-1");
Thread t4 = new Thread(() -> [Link]("Lambda Thread"), "Worker-2");
[Link](); [Link]();
}
}

THREAD SYNCHRONIZATION — Race Condition Problem & Fix:


class BankAccount {
private int balance = 1000;

// WITHOUT sync — PROBLEM: two threads may both read 1000, both withdraw 800
// void withdraw(int amt){ if(balance>=amt) balance-=amt; }

// WITH sync — SOLUTION: only one thread executes at a time


synchronized void withdraw(int amt){
if(balance >= amt){
[Link]([Link]().getName()+" withdrawing "+amt);
balance -= amt;
[Link]("Remaining: "+balance);
} else {
[Link]([Link]().getName()+" — Insufficient!");
}
}
}

class WithdrawThread extends Thread {


BankAccount acc; int amount;
WithdrawThread(BankAccount a, int amt){ acc=a; amount=amt; }
public void run(){ [Link](amount); }
}

public class SyncDemo {


public static void main(String[] args){
BankAccount acc = new BankAccount();
WithdrawThread t1 = new WithdrawThread(acc, 800);
WithdrawThread t2 = new WithdrawThread(acc, 800);
[Link](); [Link]();
// Without sync: both might succeed; With sync: only one succeeds
}
}

Thread priorities: [Link](Thread.MAX_PRIORITY); // 10


Thread states: [Link]() returns NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING,
TERMINATED.

Q2. Explain the Java Collections Framework with examples of List, Set, and Map.
COLLECTION HIERARCHY:
Iterable → Collection → List (ArrayList, LinkedList, Vector, Stack)
→ Set (HashSet, LinkedHashSet, TreeSet)
→ Queue (LinkedList, PriorityQueue, ArrayDeque)
Map (separate hierarchy): HashMap, LinkedHashMap, TreeMap, Hashtable

LIST EXAMPLE (ArrayList):


import [Link].*;
ArrayList list = new ArrayList<>();
[Link]("Apple"); [Link]("Banana"); [Link]("Cherry");
[Link](1, "Apricot"); // Insert at index 1
[Link]("Banana"); // Remove by value
[Link]([Link](0)); // Apple
[Link](list); // Sort alphabetically
[Link](list); // [Apple, Apricot, Cherry]
Iterator it = [Link]();
while([Link]()) [Link]([Link]());

SET EXAMPLE (HashSet + TreeSet):


HashSet hset = new HashSet<>();
[Link](30); [Link](10); [Link](20); [Link](10); // duplicate ignored
[Link](hset); // [20, 10, 30] — no order guaranteed

TreeSet tset = new TreeSet<>(hset);


[Link](tset); // [10, 20, 30] — sorted

MAP EXAMPLE (HashMap + TreeMap):


HashMap scores = new HashMap<>();
[Link]("Alice", 95); [Link]("Bob", 87); [Link]("Charlie", 92);
[Link]("Alice", 98); // updates existing key
[Link]([Link]("Bob")); // 87
[Link]([Link]("Alice")); // true
for([Link] entry : [Link]())
[Link]([Link]()+" : "+[Link]());

TreeMap tmap = new TreeMap<>(scores);


[Link](tmap); // sorted by key: {Alice=98, Bob=87, Charlie=92}

QUEUE EXAMPLE:
Queue q = new LinkedList<>();
[Link]("Task1"); [Link]("Task2"); [Link]("Task3");
[Link]([Link]()); // Task1 (FIFO)
[Link]([Link]()); // Task2 (no remove)

COLLECTIONS UTILITY CLASS:


List nums = new ArrayList<>([Link](5,2,8,1,9,3));
[Link](nums); // [1,2,3,5,8,9]
[Link](nums); // [9,8,5,3,2,1]
[Link]([Link](nums)); // 9
[Link]([Link](nums)); // 1
[Link](nums); // random order

VERY LONG ANSWER QUESTIONS (15 Marks)

Q1. Write a comprehensive Java program demonstrating: Multithreading (Producer-Consumer),


Exception Handling, Collections Framework, and Java Beans concept.
// ■■■■ PART 1: JAVA BEAN ■■■■
import [Link];

class ProductBean implements Serializable {


private static final long serialVersionUID = 1L;
private int id;
private String name;
private double price;
private int quantity;

// No-arg constructor (Java Bean requirement)


public ProductBean(){}

// Parameterized constructor
public ProductBean(int id, String name, double price, int qty){
[Link]=id; [Link]=name; [Link]=price; [Link]=qty;
}

// Getters and Setters (Java Bean requirement)


public int getId(){ return id; }
public void setId(int id){ [Link]=id; }
public String getName(){ return name; }
public void setName(String name){ [Link]=name; }
public double getPrice(){ return price; }
public void setPrice(double price){
if(price < 0) throw new IllegalArgumentException("Price cannot be negative!");
[Link]=price;
}
public int getQuantity(){ return quantity; }
public void setQuantity(int quantity){ [Link]=quantity; }

@Override
public String toString(){
return [Link]("Product[%d] %s | Price:%.2f | Qty:%d", id,name,price,quantity);
}
}

// ■■■■ PART 2: CUSTOM EXCEPTIONS ■■■■


class InsufficientStockException extends Exception {
public InsufficientStockException(String msg){ super(msg); }
}
class InvalidProductException extends RuntimeException {
public InvalidProductException(String msg){ super(msg); }
}

// ■■■■ PART 3: INVENTORY (Collections) ■■■■


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

class Inventory {
private HashMap products = new HashMap<>();

public void addProduct(ProductBean p){


if(p == null) throw new InvalidProductException("Product cannot be null!");
if([Link]() < 0) throw new InvalidProductException("Invalid price!");
[Link]([Link](), p);
[Link]("Added: " + p);
}

public synchronized void sell(int productId, int qty)


throws InsufficientStockException {
if(![Link](productId))
throw new InvalidProductException("Product ID "+productId+" not found!");
ProductBean p = [Link](productId);
if([Link]() < qty)
throw new InsufficientStockException(
"Only "+[Link]()+" units of '"+[Link]()+"' available!");
[Link]([Link]() - qty);
[Link]([Link]().getName()+" sold "+qty+" of "+[Link]());
}

public void displayAll(){


[Link]("\n=== INVENTORY ===");
TreeMap sorted = new TreeMap<>(products);
[Link]().forEach([Link]::println);
double totalValue = [Link]().stream()
.mapToDouble(p -> [Link]()*[Link]()).sum();
[Link]("Total Inventory Value: Rs.%.2f%n", totalValue);
}

public List getExpensiveProducts(double minPrice){


return [Link]().stream()
.filter(p -> [Link]() >= minPrice)
.sorted([Link](ProductBean::getPrice).reversed())
.collect([Link]());
}
}

// ■■■■ PART 4: PRODUCER-CONSUMER (Multithreading) ■■■■


import [Link].*;

class OrderQueue {
private Queue queue = new LinkedList<>();
private int capacity = 5;

public synchronized void produce(String order) throws InterruptedException {


while([Link]() == capacity){
[Link]("Queue full! Producer waiting...");
wait();
}
[Link](order);
[Link]([Link]().getName()+" produced: "+order);
notifyAll();
}

public synchronized String consume() throws InterruptedException {


while([Link]()){
[Link]("Queue empty! Consumer waiting...");
wait();
}
String order = [Link]();
[Link]([Link]().getName()+" consumed: "+order);
notifyAll();
return order;
}
}

class Producer implements Runnable {


OrderQueue q; String[] orders;
Producer(OrderQueue q, String[] orders){ this.q=q; [Link]=orders; }
public void run(){
for(String o : orders){
try{ [Link](o); [Link](500); }
catch(InterruptedException e){ [Link]().interrupt(); }
}
}
}

class Consumer implements Runnable {


OrderQueue q; int count;
Consumer(OrderQueue q, int c){ this.q=q; count=c; }
public void run(){
for(int i=0; i try{ [Link](); [Link](800); }
catch(InterruptedException e){ [Link]().interrupt(); }
}
}
}

// ■■■■ MAIN CLASS ■■■■


public class InventorySystem {
public static void main(String[] args){
Inventory inv = new Inventory();

// Add products using Java Bean


[Link](new ProductBean(1,"Laptop",45000,10));
[Link](new ProductBean(2,"Mouse",500,50));
[Link](new ProductBean(3,"Keyboard",1200,30));
[Link](new ProductBean(4,"Monitor",15000,8));

// Exception handling demo


try{
ProductBean p = new ProductBean();
[Link](-100); // throws IllegalArgumentException
} catch(IllegalArgumentException e){
[Link]("Caught: " + [Link]());
} finally {
[Link]("Finally block executed");
}

// Try-with-resources (Exception handling)


try{
[Link](1, 5); // OK
[Link](2, 100); // Throws InsufficientStockException
} catch(InsufficientStockException e){
[Link]("Stock Error: " + [Link]());
} catch(InvalidProductException e){
[Link]("Product Error: " + [Link]());
}

// Collections demo
[Link]();
[Link]("\nExpensive products (>5000):");
[Link](5000).forEach([Link]::println);

// Collections
ArrayList promos = new ArrayList<>();
[Link](new ProductBean(5,"Webcam",2000,20));
[Link](promos, [Link](ProductBean::getName));

// Producer-Consumer multithreading
OrderQueue orderQ = new OrderQueue();
String[] orders = {"Order#101","Order#102","Order#103","Order#104","Order#105"};
Thread producer = new Thread(new Producer(orderQ,orders),"PRODUCER");
Thread consumer = new Thread(new Consumer(orderQ,5),"CONSUMER");
[Link](); [Link]();
try{ [Link](); [Link](); }
catch(InterruptedException e){ [Link](); }

[Link]("\nAll operations completed!");


}
}

// KEY CONCEPTS DEMONSTRATED:


// Java Bean: ProductBean with private fields, getters/setters, Serializable, toString()
// Custom Exceptions: Checked (InsufficientStockException), Unchecked (InvalidProductException)
// Exception Handling: try-catch-finally, multiple catch, throw, method-level throws
// Collections: HashMap (inventory), TreeMap (sorted), ArrayList, stream API (filter/sort)
// Multithreading: Producer-Consumer pattern using wait()/notifyAll()
// Synchronization: synchronized method on sell() and produce()/consume()
// Thread join: main thread waits for producer/consumer to finish
End of Java Programming BCA Question Bank
Prof. Rajendra Singh (Rajju Bhaiya) University, Prayagraj

You might also like