Object Oriented Programming
Using Java
DCCA212 — II Semester | Even Semester 2025–2026
Complete Question Bank with Exam-Ready Answers
2-Mark · 5-Mark · 10-Mark (Programs)
Unit Topics Covered
Unit I Basics of Java, OOP Concepts, Data Types, Constructors, Arrays, Strings
Unit II Inheritance, Polymorphism, Interfaces, Packages, I/O Streams
Unit III Event Handling, GUI, Layout Managers, Applets, Strings
Unit IV Exception Handling, Multithreading, Collections, Generics, JavaBeans
UNIT – I
Basics of Java, OOP Concepts, Data Types, Constructors, Arrays, Strings
2-Mark Questions
1. Define object-oriented programming.
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around data (objects) rather than functions and logic. An object bundles together
related data (fields) and behavior (methods). OOP is built on four principles: Encapsulation
(hiding data), Inheritance (reusing code from parent classes), Polymorphism (same
interface, different behavior), and Abstraction (hiding complexity). Java is a purely
object-oriented language where everything is modeled as a class or object.
2. Difference between POP and OOP?
POP: Program divided into functions; data flows freely; top-down design; no
encapsulation/inheritance; examples: C, Pascal.
OOP: Program divided into objects that bundle data and behavior; data protected via access
modifiers; bottom-up design; supports all 4 OOP principles; examples: Java, C++, Python.
OOP is preferred for large, scalable, maintainable software.
3. List any two features of Java.
1. Platform Independent: Java source code compiles to bytecode (.class) that runs on any
machine with a JVM installed — 'Write Once, Run Anywhere.'
2. Object-Oriented: Everything in Java is modeled as objects and classes. It supports
encapsulation, inheritance, polymorphism, and abstraction fully.
4. What is a class in Java?
A class is a user-defined blueprint or template from which objects are created. It defines
attributes (fields) and behaviors (methods) that all objects of that type will have. A class itself
does not occupy memory — memory is allocated only when an object is created. Example:
class Car { String brand; void drive() { } }
5. What is an object?
An object is a runtime instance of a class. It has state (field values), behavior (method calls),
and identity (unique memory address). Created using the 'new' keyword: Car c = new Car();
Each object has its own copy of instance variables.
6. Define JVM.
JVM (Java Virtual Machine) is an abstract machine providing a runtime environment where
Java bytecode executes. It is platform-specific but the bytecode it runs is
platform-independent. JVM responsibilities: Class Loader, Bytecode Verifier, Interpreter, JIT
Compiler, and Garbage Collector.
7. What is JDK?
JDK (Java Development Kit) is the complete development environment for Java. It contains:
JRE (runtime + JVM + libraries), javac (compiler), jdb (debugger), javadoc (documentation
generator), jar (packaging tool). Relationship: JDK ⊃ JRE ⊃ JVM.
8. What are data types in Java?
Primitive: byte (1B), short (2B), int (4B), long (8B), float (4B), double (8B), char (2B), boolean
(1bit) — store values directly.
Non-Primitive (Reference): String, Arrays, Classes, Interfaces — store memory addresses to
objects in heap.
9. What is a variable?
A variable is a named memory location storing a value. Types: Local — declared inside a
method, exists only there. Instance — declared in class outside methods, each object has its
own copy. Static — declared with static keyword, shared across all objects.
10. Define control structure.
Control structures determine the flow of execution. Types: Sequential — default line-by-line.
Selection — if, if-else, switch. Repetition — for, while, do-while, for-each. Jump — break,
continue, return.
11. What is a loop?
A loop repeatedly executes a block of code while a condition is true. Java loops: for — when
iteration count is known. while — condition checked before each iteration. do-while —
executes body at least once, checks condition after. for-each — iterates over arrays and
collections.
12. What is a constructor?
A constructor is a special method with the same name as the class and no return type. It is
called automatically when an object is created with 'new'. Used to initialize object state. Types:
Default (no-arg), Parameterized, Copy constructor.
13. What is a method?
A method is a named block of code inside a class that performs a task. It has a return type (or
void), name, optional parameters, and a body. Methods enable code reuse. Types: Instance
methods, Static methods, Abstract methods.
14. What is the use of this keyword?
'this' refers to the current object. Uses: (1) Resolve name conflict — [Link] = name. (2)
Constructor chaining — this(params) as first statement. (3) Pass current object —
method(this). (4) Return current object — return this (method chaining).
15. Define wrapper class.
Wrapper classes wrap primitives as objects: int→Integer, double→Double, char→Character,
boolean→Boolean, etc. Needed for Collections (require objects, not primitives). Autoboxing:
auto primitive→wrapper. Unboxing: auto wrapper→primitive. Useful methods:
[Link](), [Link](), Integer.MAX_VALUE.
16. What is type casting?
Type casting converts one data type to another. Widening (implicit): smaller→larger, no data
loss, auto. Example: int i=10; double d=i; Narrowing (explicit): larger→smaller, data loss
possible, requires cast operator. Example: int i=(int)3.99; gives 3.
17. What is an instanceof operator?
instanceof is a binary operator checking if an object is an instance of a class/interface. Returns
boolean. Syntax: obj instanceof ClassName. Used before downcasting to avoid
ClassCastException. Example: if(a instanceof Dog) { Dog d = (Dog) a; }
18. What is an array in Java?
An array is a fixed-size ordered collection of same-type elements. Arrays are objects stored in
heap. Declared: int[] arr; Initialized: new int[5] or {1,2,3}. Zero-indexed. Size via [Link].
Supports 1D, 2D, array of objects.
19. What is String class?
String is a [Link] class representing an immutable sequence of characters. Immutable
means content cannot change — modifications create new objects. Stored in String Pool for
memory optimization. Key methods: length(), charAt(), substring(), indexOf(), equals(),
compareTo(), replace(), split(), trim().
20. What is StringBuffer?
StringBuffer is a mutable, thread-safe character sequence in [Link]. Content can be
modified without creating new objects — faster than String for repeated changes. All methods
synchronized. Key methods: append(), insert(), delete(), replace(), reverse(), toString().
StringBuilder is the non-synchronized (faster) alternative.
5-Mark Questions
1. Compare procedure-oriented and object-oriented programming paradigms.
In Procedure-Oriented Programming (POP), a program is divided into a collection of
functions or procedures. The entire focus is on the sequence of actions (algorithms) the
program must perform. Data is treated as secondary and flows freely between functions,
making it vulnerable and insecure. There is no mechanism to bind data and functions together.
Programs are designed top-down — you start with the overall problem and break it into smaller
sub-functions. Reuse is limited to calling functions. It is difficult to model real-world entities.
Examples of POP languages are C, Pascal, and FORTRAN. In Object-Oriented
Programming (OOP), the program is modeled as a collection of objects, each representing a
real-world entity. An object bundles its own data (attributes) and the functions (methods) that
operate on that data into a single unit. Data is protected from external interference through
encapsulation and access modifiers. OOP follows a bottom-up design approach — you model
the individual objects first and build up the system. Code reuse is achieved through
inheritance. Flexibility is achieved through polymorphism. Complexity is managed through
abstraction. Examples: Java, C++, Python, C#. Key Differences: Focus: POP is
function-centric; OOP is data-centric. Security: POP has no data hiding; OOP protects data via
encapsulation. Design: POP is top-down; OOP is bottom-up. Reuse: POP has limited reuse;
OOP promotes reuse via inheritance. Scalability: POP is hard to maintain for large systems;
OOP scales well. Real-world modeling: POP is abstract; OOP maps directly to real-world
entities. OOP is the preferred paradigm for complex, real-world, long-lived software systems.
2. Explain the features of Java.
Java has a rich set of features that make it one of the world's most popular programming
languages. 1. Simple: Java has clean, easy-to-understand syntax modeled on C/C++ but
eliminates complex and error-prone features like explicit pointers, operator overloading, and
multiple class inheritance. This simplicity reduces bugs and makes code easier to read and
maintain. 2. Object-Oriented: Java strictly follows all four OOP principles — encapsulation,
inheritance, polymorphism, and abstraction. Everything in Java is an object (except primitives),
enabling modular, reusable, and maintainable code design. 3. Platform Independent: Java
source code (.java) is compiled by javac into bytecode (.class). This bytecode is not tied to any
specific hardware or operating system — it can run on any platform that has a Java Virtual
Machine (JVM) installed. This is the famous 'Write Once, Run Anywhere' (WORA) principle. 4.
Secure: Java does not support explicit pointers, preventing unauthorized memory access. The
JVM verifies bytecode before execution. Java also provides a sandbox environment and
security manager for running untrusted code. 5. Robust: Java has strong compile-time type
checking, a powerful exception handling framework (try-catch-finally), and automatic garbage
collection that prevents memory leaks. These features make Java programs reliable and
crash-resistant. 6. Multithreaded: Java has built-in support for multithreading via the Thread
class and Runnable interface, allowing multiple parts of a program to run concurrently and
improving performance on multi-core processors. 7. High Performance: The JIT
(Just-In-Time) compiler within the JVM identifies frequently executed bytecode at runtime and
compiles it to native machine code, greatly improving execution speed over pure interpretation.
8. Distributed: Java was designed with network programming in mind. It provides APIs for
TCP/IP networking ([Link]), Remote Method Invocation (RMI), and JDBC for database
access, making distributed application development straightforward.
3. Describe the structure of a Java program.
Every Java program follows a well-defined structure that the compiler and JVM expect.
Understanding this structure is fundamental to writing any Java program. 1. Package
Declaration (Optional): The very first statement in a Java file (if present). Groups related
classes into a namespace. Example: package [Link]; If omitted, the class belongs to
the unnamed default package. 2. Import Statements (Optional): Follow the package
declaration. Tell the compiler which external classes or packages this file uses. Example:
import [Link]; import [Link].*; The [Link] package is auto-imported and never
needs an explicit import. 3. Class Declaration: Every Java file must contain at least one class.
The public class name must exactly match the file name. Example: public class StudentDemo {
} All code lives inside class declarations. 4. Instance Variables (Fields): Declared inside the
class but outside any method. They represent the state of each object. Example: String name;
int age; 5. Constructors: Special methods called when objects are created with new. Used to
initialize fields. Can be overloaded for different initialization options. 6. Instance and Static
Methods: Define the behavior of the class. Can return values or be void. Encapsulate
reusable logic. 7. The main() Method: The mandatory entry point for a standalone Java
application. JVM starts execution here. Signature must be exactly: public static void
main(String[] args). public — accessible to JVM, static — called without object, void — returns
nothing, String[] args — command-line arguments. Structure summary: package → imports →
class { fields → constructors → methods → main() }. This consistent structure makes Java
code organized and readable across all projects and developers.
4. Explain different data types in Java with examples.
Java provides two categories of data types — primitive and non-primitive (reference) types.
Primitive Data Types (8 types): These are the fundamental building blocks of data in Java.
They store actual values directly in stack memory. byte: 1 byte, range -128 to 127. Used for
small integer values and saving memory in large arrays. Example: byte age = 25; short: 2
bytes, range -32,768 to 32,767. Example: short year = 2026; int: 4 bytes, range about ±2
billion. The default and most commonly used integer type. Example: int salary = 50000; long:
8 bytes, for very large integers. Suffix L required. Example: long population = 8000000000L;
float: 4 bytes, single-precision decimal. Suffix f required. Example: float price = 99.99f;
double: 8 bytes, double-precision decimal. Default type for decimal numbers. Example:
double pi = 3.14159265; char: 2 bytes, single Unicode character in single quotes. Example:
char grade = 'A'; boolean: 1 bit, only true or false. Used for conditions and flags. Example:
boolean isLoggedIn = true; Non-Primitive (Reference) Data Types: These store memory
addresses pointing to objects in heap memory, not the values themselves. String: Represents
a sequence of characters. Example: String name = "Java"; Array: Fixed-size collection of
same-type elements. Example: int[] marks = {80, 90, 75}; Class: User-defined type. Example:
Student s = new Student(); Interface: Abstract type defining a contract for classes to
implement. Choosing the correct data type impacts memory efficiency, computation accuracy,
and program correctness. Use int for whole numbers, double for decimals, boolean for
conditions, and String for text.
5. Discuss control structures in Java.
Control structures are programming constructs that determine the order of execution of
statements. Without them, every program would run sequentially from first line to last, which is
insufficient for any real logic. 1. Sequential Execution: Default flow — statements execute
one after another, top to bottom. This is the baseline from which other control structures
deviate. 2. Selection / Decision Structures: if statement: Executes a block only if a boolean
condition is true. Example: if (marks >= 50) { [Link]("Pass"); } if-else: Executes
one of two blocks based on condition. Example: if (n % 2 == 0) { ... } else { ... } else-if ladder:
Chain of conditions tested in order. Only the first matching block runs. Used for multiple
exclusive conditions. switch statement: Tests a variable against multiple constant values
using case labels. More readable than a long else-if chain for discrete values. Uses break to
exit, default for no match. 3. Repetition / Loop Structures: for loop: Used when iteration
count is known. Syntax: for(int i=0; i<n; i++). Compact — init, condition, update in one line.
while loop: Tests condition before each iteration. Used when count is unknown. Syntax:
while(condition) { body; } do-while loop: Executes body first, then tests condition. Guarantees
minimum one execution. Used for menu-driven programs. for-each loop: Iterates over all
elements of an array or collection without index management. Syntax: for(int x : arr). 4. Jump
Statements: break: Immediately exits current loop or switch block. continue: Skips remaining
statements in current iteration, jumps to next iteration. return: Exits the current method,
optionally returning a value to the caller.
6. Explain looping constructs with examples.
Loops are control structures that execute a block of code repeatedly as long as a condition
holds. They are fundamental for processing arrays, reading input, performing calculations, and
automating repetitive tasks. 1. for Loop: Best used when the number of iterations is known.
The initialization, condition check, and update expression are all written in a single compact
line. Syntax: for(initialization; condition; update) { body; } Example: for(int i = 1; i <= 5; i++) {
[Link]("Count: " + i); } Execution trace: i=1 (print 1), i=2 (print 2), ..., i=5 (print 5),
i=6 (condition false, loop ends). Also supports multiple variables: for(int i=0, j=10; i<j; i++, j--).
2. while Loop: Best used when the iteration count is not known in advance. Condition is
evaluated before every iteration. If false from the start, body never executes. Syntax:
while(condition) { body; } Example: int n = 1; while(n <= 100) { sum += n; n++; } — sums 1 to
100. 3. do-while Loop: The body executes first, then the condition is checked. This
guarantees the body runs at least once regardless of the condition. Ideal for menus — show
the menu, then ask if user wants to continue. Syntax: do { body; } while(condition); Example:
do { [Link]("Menu shown"); choice = [Link](); } while(choice != 0); 4.
Enhanced for (for-each) Loop: Introduced in Java 5. Provides a cleaner way to iterate over
arrays and Collection objects without needing an index variable. Read-only iteration. Syntax:
for(DataType var : arrayOrCollection) { body; } Example: int[] arr = {10, 20, 30, 40}; for(int x :
arr) { [Link](x); } Nested Loops: A loop inside another loop. Used for 2D arrays,
pattern printing, and matrix operations. Total iterations = outer_count × inner_count per outer
iteration.
7. Differentiate between methods and constructors.
Both methods and constructors are members of a Java class, but they serve completely
different purposes. Constructor: A constructor is a special block of code that is invoked
automatically by the JVM when an object is created using the new keyword. Its sole purpose is
to initialize the newly created object — setting initial values for instance variables and
performing any setup needed before the object is used. A constructor must have exactly the
same name as the class and has NO return type — not even void. If you don't define any
constructor, Java automatically provides a default no-argument constructor. Multiple
constructors can exist in a class (constructor overloading) to allow different initialization
options. Constructors are NOT inherited by subclasses, but a subclass can call the superclass
constructor using super(). Calling another constructor of the same class is done with this() as
the very first statement. Method: A method is a named block of code that defines the behavior
or operations of an object. Methods are called explicitly by the programmer when some
operation needs to be performed. A method must specify a return type (which can be void if it
returns nothing). Methods can have any name (except the class name). Methods are inherited
by subclasses and can be overridden to provide different behavior. Methods are not called
automatically — they require explicit invocation through an object or class reference.
Summary of Key Differences: Name: Constructor = class name; Method =
programmer-chosen name. Return type: Constructor = none; Method = required (int, void,
etc.). Invocation: Constructor = automatic on new; Method = explicit call. Purpose: Constructor
= initialize object state; Method = define behavior. Inheritance: Constructor = not inherited;
Method = inherited. Default: Constructor = Java provides default if none defined; Method = no
default. Overriding: Constructor = cannot be overridden; Method = can be overridden.
8. Explain wrapper classes with examples.
Wrapper classes convert primitive data types into objects, enabling them to be used anywhere
an object is required in Java. The Eight Wrapper Classes: byte → Byte, short → Short, int →
Integer, long → Long, float → Float, double → Double, char → Character, boolean → Boolean.
All are in the [Link] package and are automatically imported. Why Wrapper Classes Are
Needed: Java's Collections Framework (ArrayList, HashMap, HashSet, etc.) can only store
objects, not primitives. Without wrapper classes, you couldn't store an int in an ArrayList. With
wrappers: ArrayList<Integer> list = new ArrayList<>(); [Link](42); works perfectly.
Autoboxing (Java 5+): Java automatically converts a primitive to its wrapper object when
needed. This conversion happens transparently — no explicit code required. Example: Integer
i = 100; — Java silently converts int 100 to an Integer object. Example: [Link](5); — Java
autoboxes int 5 to Integer before adding to list. Unboxing (Java 5+): Java automatically
converts a wrapper object back to its primitive when needed. Example: int x = i; — Java silently
unboxes Integer i to int. Example: int sum = [Link](0) + [Link](1); — both Integer objects
unboxed to int for arithmetic. Useful Utility Methods: [Link]("123") — converts
String "123" to int 123. [Link](456) — converts int 456 to String "456".
Integer.MAX_VALUE, Integer.MIN_VALUE — constant boundary values.
[Link]("3.14") — converts String to double. [Link]('5') — returns true
(is a digit). [Link]('A') — returns true (is a letter). [Link]('a') —
returns 'A'. [Link]("true") — converts String to boolean.
9. Describe String and StringBuffer classes.
Both String and StringBuffer handle text in Java but differ fundamentally in mutability and
performance. String Class ([Link]): String represents an immutable sequence of
characters. Once a String object is created, its character content can never be changed. Any
operation that appears to modify a String (like concatenation, replace, or toUpperCase)
actually creates and returns a brand new String object. The original String object remains
unchanged in memory. This immutability has several benefits: String objects are inherently
thread-safe (multiple threads can read the same String safely), Java can optimize memory
using the String Pool (where identical string literals are stored once and shared), and String
objects can safely be used as HashMap keys because their hashCode never changes. The
downside of immutability: building a String through many concatenations in a loop creates
many short-lived temporary objects, which wastes memory and slows execution. Important
String methods: length(), charAt(i), substring(start, end), indexOf(str), contains(str), equals(str),
equalsIgnoreCase(str), compareTo(str), toUpperCase(), toLowerCase(), trim(), replace(old,
new), split(regex), [Link](fmt, args). StringBuffer Class ([Link]):
StringBuffer represents a mutable character sequence. It maintains an internal char array that
can be modified in place — characters can be added, removed, replaced, or reversed without
creating new objects. This makes StringBuffer highly efficient for scenarios involving many
string modifications, such as building a large SQL query, assembling a report, or processing
text in a loop. StringBuffer is thread-safe: all its methods are synchronized, meaning only one
thread can modify it at a time. This makes it safe for multi-threaded programs at the cost of
slightly lower performance. StringBuilder (Java 5) provides the same API without
synchronization — faster for single-threaded use. Important StringBuffer methods: append(x),
insert(index, str), delete(start, end), replace(start, end, str), reverse(), charAt(i), setCharAt(i, c),
length(), capacity(), toString().
10. Explain type casting in Java.
Type casting is the process of converting a value from one data type to another compatible
type. Java is a strongly-typed language — every variable has a fixed declared type, and type
casting provides the mechanism to work across type boundaries. 1. Widening (Implicit)
Casting — Automatic: Widening converts a smaller, less capable data type into a larger one.
Because no precision or magnitude is lost, Java performs this conversion silently and
automatically without any programmer intervention. The widening hierarchy is: byte → short →
int → long → float → double. You can also widen char to int (gets the Unicode code point
value). Example: int i = 500; double d = i; — d becomes 500.0 automatically, no cast needed.
Example: char c = 'A'; int ascii = c; — ascii becomes 65. 2. Narrowing (Explicit) Casting —
Manual: Narrowing converts a larger type to a smaller one. Since data loss is possible
(decimal truncation, integer overflow), Java requires the programmer to explicitly acknowledge
the conversion using a cast operator of the form (TargetType) before the value. Example:
double pi = 3.99159; int n = (int) pi; — n becomes 3 (decimal part discarded). Example: int
large = 300; byte b = (byte) large; — b gets an overflowed value (300 mod 256 = 44). 3.
Object (Reference) Type Casting: Used in inheritance hierarchies to convert between related
class types. Upcasting: Assigning a subclass object to a superclass reference. Always safe,
done implicitly. Animal a = new Dog(); — Dog IS-A Animal, so no explicit cast needed.
Through the Animal reference, only Animal's methods are accessible (not Dog-specific ones).
Downcasting: Casting a superclass reference back to the specific subclass type. Requires
explicit cast and can throw ClassCastException at runtime if the actual object is not of that
type. Dog d = (Dog) a; — safe only if 'a' actually refers to a Dog object. Always use instanceof
before downcasting: if(a instanceof Dog) { Dog d = (Dog) a; }
11. Discuss the role of JVM and JDK.
JVM (Java Virtual Machine): The JVM is the foundation of Java's famous platform
independence. It is an abstract computing machine — a software layer that sits between the
compiled Java bytecode and the physical hardware. When you compile a Java program with
javac, the output is a .class file containing bytecode — instructions that are not for any specific
CPU, but for the JVM. Since every major operating system has its own JVM implementation,
the same .class file runs on Windows, Linux, macOS, or any other platform without
recompilation. This is the essence of 'Write Once, Run Anywhere.' Key JVM Components:
Class Loader Subsystem: Finds and loads .class files into memory at runtime. Has three
phases: loading (finding the bytecode), linking (verification, preparation, resolution), and
initialization (running static initializers). Bytecode Verifier: Verifies that loaded bytecode is
valid, well-formed, and doesn't violate Java's type safety rules before execution begins. This is
a key security check. Execution Engine: Contains the Interpreter (executes bytecode
instructions one-by-one) and the JIT (Just-In-Time) Compiler (identifies 'hot'
frequently-executed code paths and compiles them to native machine code for speed).
Garbage Collector: Automatically identifies and reclaims memory used by objects no longer
reachable by the program, preventing memory leaks without programmer intervention.
Runtime Data Areas: Heap (all objects stored here), Stack (one per thread, stores method
frames and local variables), Method Area (class metadata, static variables), PC Register,
Native Method Stack. JDK (Java Development Kit): The JDK is the complete development
toolkit needed to create Java applications. It is a superset: JDK contains JRE, which contains
JVM. The JDK adds development tools on top of the runtime. JDK components: JRE (runtime
environment with JVM + standard class libraries), javac (compiler transforming .java to .class),
java (launcher that starts JVM to run bytecode), javadoc (generates HTML API documentation
from source comments), jdb (interactive debugger), jar (packages classes into distributable .jar
archives), jshell (interactive REPL for experimenting with Java code, Java 9+). Developers
need the full JDK. End users who only run Java applications only need the JRE.
12. Explain the use of this keyword.
The 'this' keyword in Java is a special reference variable implicitly available in every instance
method and constructor. It always refers to the current object — the specific instance on which
the method or constructor is currently executing. It is NOT available in static methods because
static methods belong to the class, not to any specific instance. Use 1 — Resolving Instance
Variable vs. Local Variable Name Conflict: When a constructor or method parameter has
the same name as an instance variable, the local parameter shadows (hides) the instance
variable within that scope. Using 'this.' explicitly refers to the instance variable, distinguishing it
from the local parameter. Example: Employee(String name, double salary) { [Link] =
name; [Link] = salary; } — without 'this', the assignment would be a no-op (name = name
sets the local to itself). Use 2 — Constructor Chaining within Same Class: One constructor
can invoke another constructor in the same class using this() with the appropriate arguments.
This eliminates duplicated initialization code across multiple constructors. The this() call must
be the very first statement in the calling constructor. Example: Employee() { this("Unknown",
0.0); } — delegates to the full constructor. Use 3 — Passing the Current Object as an
Argument: 'this' can be passed to a method or another object that requires a reference to the
current object. This is useful for registering an object with an external system, or implementing
the Observer pattern. Example: [Link](this); — registers the current object as
an event listener. Use 4 — Method Chaining (Returning the Current Object): When a setter
or builder method returns 'this', it allows multiple method calls to be chained together on a
single object in one expression. Example:
[Link]("Java").setVersion(21).setLTS(true).build(); — each setter returns 'this'. Use
5 — Inner Class Access to Outer Class: In non-static inner classes, [Link] refers
explicitly to the outer class instance, distinguishing it from the inner class's own 'this'.
13. Describe arrays in Java with example.
An array in Java is a fixed-size, ordered container object that holds a specific number of values
all of the same data type. Arrays are objects stored in heap memory, and the array variable
holds a reference to this heap object. Declaration: int[] arr; — declares a reference variable
that can point to an integer array (no memory allocated yet). Alternative syntax: int arr[]; —
legal but the first form is preferred. Initialization: Static: int[] arr = {10, 20, 30, 40, 50}; — size
and values determined by the initializer. Dynamic: int[] arr = new int[5]; — allocates heap
space for 5 integers, all initialized to 0. Default Values: int/byte/short/long = 0, float/double =
0.0, boolean = false, char = '■' (null char), object references = null. Key Properties:
Zero-indexed: first element is arr[0], last is arr[[Link] - 1]. Fixed size: once created, the
array's size cannot change (use ArrayList for dynamic sizing). Length: [Link] is a public
final field (not a method — no parentheses). Accessing and Iterating: By index: arr[2] = 100;
[Link](arr[0]); With for loop: for(int i=0; i<[Link]; i++) { [Link](arr[i]);
} With for-each: for(int x : arr) { [Link](x); } Multi-Dimensional Arrays: 2D: int[][]
matrix = new int[3][3]; — 3 rows, 3 columns. Access: matrix[row][col]. Jagged arrays: each row
can have different length. int[][] jagged = new int[3][]; jagged[0] = new int[2]; Array of Objects:
Student[] students = new Student[3]; — creates array holding 3 Student references (all null
initially). students[0] = new Student("Alice", 20); — must initialize each element individually.
[Link] Utility Class: [Link](arr), [Link](arr, key), [Link](arr,
value), [Link](arr, len), [Link](arr) for display.
14. Explain built-in classes in Java.
Java ships with a vast standard library organized into packages. These built-in classes provide
tested, optimized implementations of common functionality. [Link] Package
(auto-imported): Object: The root superclass of every Java class. Provides equals(),
hashCode(), toString(), getClass(), clone(), finalize(). When you override toString() in your
class, [Link](obj) prints your custom representation. String: Immutable character
sequences with a rich API for text manipulation. StringBuffer / StringBuilder: Mutable
character sequences for efficient text building. Math: Static mathematical methods —
[Link](x), [Link](x), [Link](x,y), [Link](x), [Link](x), [Link](x),
[Link](a,b), [Link](a,b), [Link]() (returns 0.0 to 1.0), [Link], Math.E. System:
[Link]() (output), [Link] (input), [Link] (error), [Link]()
(timestamp), [Link](0) (terminate), [Link]() (fast array copy). Integer,
Double, Float, Long, etc.: Wrapper classes with parsing, conversion, and limit constants.
Thread: Creates and manages concurrent threads. [Link] Package: Scanner: Reads input
from keyboard, files, or strings. Methods: nextInt(), nextDouble(), nextLine(), next(). ArrayList:
Resizable array list — add(), get(), remove(), size(), contains(), set(), sort(). HashMap:
Key-value storage — put(), get(), remove(), containsKey(), keySet(), values(). HashSet /
TreeSet: Collections of unique elements. Collections: Static utility methods —
[Link](), shuffle(), reverse(), min(), max(). Arrays: Static array utilities. Random:
nextInt(n), nextDouble(), nextBoolean() for random values. [Link] Package: File, FileReader,
FileWriter, BufferedReader, BufferedWriter, PrintWriter for file I/O. ObjectInputStream,
ObjectOutputStream for object serialization.
15. Compare String and StringBuffer.
String and StringBuffer both handle character sequences but serve different purposes based
on whether the text needs to change. Mutability: String is immutable — once created, the
content of a String object can never change. Every 'modification' (concat, replace,
toUpperCase, etc.) creates and returns a completely new String object, leaving the original
untouched. StringBuffer is mutable — it maintains a char[] buffer that can be directly modified
in place. append(), insert(), delete(), replace(), and reverse() all modify the same object without
creating new ones. Performance: This mutability difference has a major performance impact.
Consider building a string from 10,000 parts: String str = ""; for(int i=0; i<10000; i++) str += i; —
this creates 10,000 intermediate String objects, stressing the garbage collector and running
slowly. StringBuffer sb = new StringBuffer(); for(int i=0; i<10000; i++) [Link](i); — this
modifies one object efficiently, running orders of magnitude faster. Thread Safety:
StringBuffer is synchronized — all its methods are thread-safe. Multiple threads can use the
same StringBuffer safely. String is also effectively thread-safe due to immutability (no thread
can change it). StringBuilder is like StringBuffer but NOT synchronized — faster in
single-threaded programs. Memory Storage: String literals are stored in the String Pool
(interned). Identical literals share the same object: String a = "Java"; String b = "Java"; here a
and b point to the same pool object. StringBuffer and StringBuilder objects are always
allocated fresh in regular heap memory. API: String provides read-only operations (length,
charAt, substring, indexOf, contains, equals, compareTo, split, replace, format). StringBuffer
adds mutation operations: append(x), insert(i, x), delete(s, e), replace(s, e, str), reverse(),
setCharAt(i, c), toString(). Rule of Thumb: Use String for fixed text (labels, names, config
values). Use StringBuilder for single-threaded string building. Use StringBuffer for
multi-threaded string building.
10-Mark Questions (Programs)
1. Java program: Hello World and data type sizes.
public class DataTypeSizes {
public static void main(String[] args) {
[Link]("Hello, World!");
[Link]("byte : " + [Link] + " bits | " + Byte.MIN_VALUE + " to " +
Byte.MAX_VALUE);
[Link]("short : " + [Link] + " bits | " + Short.MIN_VALUE + " to " +
Short.MAX_VALUE);
[Link]("int : " + [Link] + " bits | " + Integer.MIN_VALUE + " to " +
Integer.MAX_VALUE);
[Link]("long : " + [Link] + " bits | " + Long.MIN_VALUE + " to " +
Long.MAX_VALUE);
[Link]("float : " + [Link] + " bits");
[Link]("double : " + [Link] + " bits");
[Link]("char : " + [Link] + " bits");
[Link]("boolean: 1 bit | true or false");
byte b=127; short s=32767; int i=2147483647; long l=9876543210L;
float f=3.14f; double d=3.14159; char c='J'; boolean flag=true;
[Link]("b=%d s=%d i=%d l=%d f=%.2f d=%.5f c=%c flag=%b%n",b,s,i,l,f,d,c,flag);
}
}
2. Java program: static, local, and instance variables.
public class VariablesDemo {
static String college = "BCA College"; // static variable
String name; int age; // instance variables
VariablesDemo(String n, int a) { [Link]=n; [Link]=a; }
void show() {
String status = (age>=18) ? "Adult" : "Minor"; // local variable
[Link](name + " | Age:" + age + " | " + status + " | " + college);
}
static void showCollege() { [Link]("College: " + college); }
public static void main(String[] args) {
[Link]();
VariablesDemo s1 = new VariablesDemo("Abubakar", 19);
VariablesDemo s2 = new VariablesDemo("Alice", 17);
[Link](); [Link]();
[Link]("Same college? " + ([Link] == [Link])); // true - shared
}
}
3. Java program: String operations.
public class StringOps {
public static void main(String[] args) {
String s = "Object Oriented Programming Using Java";
[Link]("Original : " + s);
[Link]("Length : " + [Link]());
[Link]("Upper : " + [Link]());
[Link]("Lower : " + [Link]());
[Link]("charAt(0) : " + [Link](0));
[Link]("indexOf J : " + [Link]("Java"));
[Link]("substr(0,6): " + [Link](0,6));
[Link]("replace : " + [Link]("Java","C++"));
[Link]("contains : " + [Link]("Java"));
[Link]("startsWith: " + [Link]("Object"));
[Link]("endsWith : " + [Link]("Java"));
String[] words = [Link](" ");
[Link]("Word count: " + [Link]);
String s1="Hello"; String s2=" World";
[Link]("Concat : " + [Link](s2));
[Link]("Trim : " + " spaces ".trim());
StringBuffer sb = new StringBuffer("Hello");
[Link](" Java").insert(5,",").reverse();
[Link]("StringBuf : " + sb);
}
}
4. Java program: maximum of three numbers.
import [Link];
public class MaxThree {
static int max(int a, int b, int c) {
if(a>=b && a>=c) return a;
else if(b>=a && b>=c) return b;
else return c;
}
public static void main(String[] args) {
[Link]("max(45,78,23) = " + max(45,78,23));
[Link]("max(99,45,60) = " + max(99,45,60));
[Link]("max(-5,-1,-9) = " + max(-5,-1,-9));
// Also using [Link]
int x=34, y=67, z=12;
int result = [Link](x, [Link](y,z));
[Link]("[Link]: " + result);
// Ternary
int maxAB = (x>y)?x:y;
int maxAll = (maxAB>z)?maxAB:z;
[Link]("Ternary : " + maxAll);
Scanner sc = new Scanner([Link]);
[Link]("Enter 3 numbers: ");
int a=[Link](), b=[Link](), c=[Link]();
[Link]("Max = " + max(a,b,c));
[Link]();
}
}
5. Java program: odd or even check.
import [Link];
public class OddEven {
public static void main(String[] args) {
int[] nums = {0,1,4,7,100,-5,-8,999};
for(int n : nums) {
[Link](n + " is " + (n%2==0 ? "Even" : "Odd"));
}
// Bitwise approach
[Link]("\n--- Bitwise ---");
[Link]("15: " + ((15&1)==1 ? "Odd" : "Even"));
[Link]("20: " + ((20&1)==1 ? "Odd" : "Even"));
// Count in range
int odd=0, even=0;
for(int i=1; i<=20; i++) { if(i%2==0) even++; else odd++; }
[Link]("1-20: Odd=" + odd + " Even=" + even);
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
int n = [Link]();
[Link](n + " is " + (n%2==0?"Even":"Odd"));
[Link]();
}
}
6. Java program: constructors demo.
public class ConstructorDemo {
String name; int age; double marks; String branch;
// Default constructor
ConstructorDemo() {
this("Unknown", 18, 0.0, "BCA");
[Link]("[Default] created");
}
// Parameterized constructor
ConstructorDemo(String name, int age, double marks, String branch) {
[Link]=name; [Link]=age; [Link]=marks; [Link]=branch;
[Link]("[Param] created: " + name);
}
// Copy constructor
ConstructorDemo(ConstructorDemo o) {
this([Link]+" (Copy)", [Link], [Link], [Link]);
}
void display() {
[Link]("Name:%-12s Age:%d Marks:%.1f Branch:%s%n",name,age,marks,branch);
}
void result() { [Link](name + ": " + (marks>=40?"PASS":"FAIL")); }
public static void main(String[] args) {
ConstructorDemo s1 = new ConstructorDemo();
ConstructorDemo s2 = new ConstructorDemo("Abubakar",19,85.5,"BCA");
ConstructorDemo s3 = new ConstructorDemo(s2);
[Link](); [Link](); [Link]();
[Link](); [Link](); [Link]();
}
}
7. Java program: array of objects.
public class ArrayOfObjects {
static class Student {
int roll; String name; double m1,m2,m3,avg;
Student(int r,String n,double a,double b,double c){
roll=r; name=n; m1=a; m2=b; m3=c; avg=(a+b+c)/3;
}
String grade(){return avg>=90?"O":avg>=75?"A":avg>=60?"B":avg>=50?"C":"F";}
void show(){[Link]("%3d | %-12s | %5.1f | %5.1f | %5.1f | %6.2f |
%s%n",roll,name,m1,m2,m3,avg,grade());}
}
public static void main(String[] args) {
Student[] s = {
new Student(101,"Abubakar",88,92,85),
new Student(102,"Alice",95,90,93),
new Student(103,"Bob",72,68,75),
new Student(104,"Charlie",45,50,48),
new Student(105,"Diana",80,85,78)
};
[Link]("%3s | %-12s | %5s | %5s | %5s | %6s |
%s%n","Roll","Name","M1","M2","M3","Avg","Grade");
[Link]("-".repeat(60));
double total=0; Student topper=s[0];
for(Student st:s){ [Link](); total+=[Link]; if([Link]>[Link]) topper=st; }
[Link]("Class Avg: " + [Link]("%.2f",total/[Link]));
[Link]("Topper : " + [Link] + " (" + [Link]("%.2f",[Link]) +
"%)");
}
}
8. Java program: this keyword.
public class ThisDemo {
String model; int year; double price;
ThisDemo(){this("Unknown",2020,0.0);[Link]("Default via this()");}
ThisDemo(String model,int year,double price){
[Link]=model; [Link]=year; [Link]=price; // use 1: resolve conflict
}
ThisDemo setModel(String m){[Link]=m; return this;} // use 4: method chaining
ThisDemo setYear(int y){[Link]=y; return this;}
ThisDemo setPrice(double p){[Link]=p; return this;}
void show(){[Link](model+" | "+year+" | Rs."+price);}
void register(){[Link]("Registering: "+model); log(this);} // use 3: pass
this
static void log(ThisDemo t){[Link]("Logged: "+[Link]);}
public static void main(String[] args){
ThisDemo t1 = new ThisDemo(); [Link]();
ThisDemo t2 = new ThisDemo("Toyota",2023,1200000); [Link]();
[Link]();
ThisDemo t3 = new ThisDemo();
[Link]("Tesla").setYear(2025).setPrice(6000000); // method chaining
[Link]();
}
}
9. Java program: type casting.
public class TypeCasting {
static class Animal { String n; Animal(String n){this.n=n;} void
sound(){[Link](n+" sound");} }
static class Dog extends Animal { Dog(String n){super(n);} void
sound(){[Link](n+": Woof!");} void fetch(){[Link](n+"
fetches");} }
static class Cat extends Animal { Cat(String n){super(n);} void
sound(){[Link](n+": Meow!");} void purr(){[Link](n+" purrs");} }
public static void main(String[] args){
// Widening (implicit)
byte b=42; short s=b; int i=s; long l=i; float f=l; double d=f;
[Link]("byte->double: "+b+" -> "+d);
char c='A'; int ascii=c; [Link]("char->int: A -> "+ascii);
// Narrowing (explicit)
double pi=3.99; int n=(int)pi; [Link]("double->int: "+pi+" -> "+n);
int big=300; byte byt=(byte)big; [Link]("int->byte overflow: "+big+" ->
"+byt);
int code=66; char ch=(char)code; [Link]("int->char: 66 -> "+ch);
// Object casting
Animal a1=new Dog("Rex"); // upcasting (implicit)
Animal a2=new Cat("Luna");
[Link](); [Link](); // polymorphism
if(a1 instanceof Dog){Dog d2=(Dog)a1; [Link]();} // downcasting (explicit)
if(a2 instanceof Cat){Cat cat=(Cat)a2; [Link]();}
try{Dog wrong=(Dog)a2;} // invalid downcast
catch(ClassCastException e){[Link]("ClassCastException: "+[Link]());}
}
}
10. Java program: String vs StringBuffer comparison.
public class StringVsBuffer {
public static void main(String[] args){
// String - immutable
String s = "Hello";
String s2 = s;
s = [Link](" World");
[Link]("s = "+s); [Link]("s2 = "+s2); // s2 unchanged
[Link]("Same object? "+(s==s2)); // false
// String pool
String a="Java", b="Java", c=new String("Java");
[Link]("a==b (pool): "+(a==b)); // true
[Link]("a==c (heap): "+(a==c)); // false
[Link]("[Link](c): "+[Link](c)); // true
// StringBuffer - mutable
StringBuffer sb = new StringBuffer("Hello");
[Link](" Java"); [Link]("append : "+sb);
[Link](5,","); [Link]("insert : "+sb);
[Link](5,6); [Link]("delete : "+sb);
[Link](6,10,"World"); [Link]("replace : "+sb);
[Link](); [Link]("reverse : "+sb);
[Link](); [Link]("restored: "+sb);
// Performance
long t1=[Link]();
String str=""; for(int i=0;i<5000;i++) str+=i;
[Link]("String concat 5000: "+([Link]()-t1)+"ms");
long t2=[Link]();
StringBuffer sbf=new StringBuffer(); for(int i=0;i<5000;i++) [Link](i);
[Link]("Buffer append 5000: "+([Link]()-t2)+"ms");
}
}
UNIT – II
Inheritance, Polymorphism, Interfaces, Packages, I/O Streams
2-Mark Questions
1. What is inheritance?
Inheritance is the mechanism by which one class (subclass) acquires the properties and
behaviors of another class (superclass) using the 'extends' keyword. It promotes code reuse
and establishes an IS-A relationship. Example: class Dog extends Animal — Dog IS-A Animal
and inherits all non-private members of Animal.
2. Define superclass and subclass.
Superclass (parent/base class): the class being inherited from; represents general
characteristics. Subclass (child/derived class): the class that inherits using 'extends'; gets all
accessible (public/protected) members of the superclass and can add its own fields/methods
or override inherited ones.
3. What are visibility modifiers?
Access modifiers control member accessibility: private — same class only. default (no
keyword) — same package only. protected — same package + subclasses anywhere. public
— everywhere. Best practice: make fields private, methods public/protected.
4. List types of inheritance.
1. Single — class B extends A. 2. Multilevel — C extends B extends A (chain). 3.
Hierarchical — B,C,D all extend A (one parent, many children). 4. Multiple — Java does not
allow via classes; achieved via interfaces. 5. Hybrid — combination, achieved via interfaces.
5. What is single inheritance?
One subclass inherits from exactly one superclass. Example: class Car extends Vehicle — Car
IS-A Vehicle, inherits all Vehicle members, can add honk(), override start(). The simplest and
most common form.
6. What is multiple inheritance?
A class inheriting from more than one parent. Java does NOT support this through classes
(Diamond Problem — ambiguity when both parents have same method). Achieved in Java via
interfaces: class C implements InterfaceA, InterfaceB.
7. What is hierarchical inheritance?
Multiple subclasses inherit from the same single superclass. Example: Dog, Cat, Bird all
extend Animal. Each inherits Animal's breathe() and eat() but adds its own unique behaviors.
8. What is hybrid inheritance?
Combination of two or more inheritance types. Java supports this through a mix of class
inheritance and multiple interface implementation to avoid the Diamond Problem.
9. What is an interface in Java?
An interface is a reference type defining a contract — WHAT to do, not HOW. Declared with
'interface' keyword. All methods implicitly public abstract (pre-Java 8). Variables are public
static final constants. A class uses 'implements' to fulfill the contract. A class can implement
multiple interfaces.
10. Define polymorphism.
Polymorphism ('many forms') allows one entity to behave differently in different contexts. Two
types: Compile-time — method overloading (resolved by compiler based on signature).
Runtime — method overriding (resolved by JVM at runtime based on actual object type).
11. What is compile-time polymorphism?
Method overloading — multiple methods with same name but different parameter lists in the
same class. Compiler resolves which method to call at compile time based on argument types.
Also called static binding. Example: add(int,int) and add(double,double).
12. What is run-time polymorphism?
Method overriding — subclass redefines a superclass method with same signature. JVM
resolves which version to call at runtime based on actual object type (not reference type).
Requires upcasting: Animal a = new Dog(); [Link]() calls Dog's speak().
13. What is method overloading?
Defining multiple methods in the same class with the same name but different parameter lists
(number, type, or order). Compiler resolves the correct one at compile time. Return type alone
is insufficient to differentiate. Example: [Link](int), [Link](double), [Link](float).
14. What is method overriding?
Subclass provides its own implementation of a superclass method with the exact same
signature (name, return type, parameters). @Override annotation recommended. Private,
static, and final methods cannot be overridden. Enables runtime polymorphism.
15. What is a package?
A package is a namespace grouping related classes/interfaces into a directory unit. Prevents
naming conflicts, controls access, and organizes code. Declared with 'package' keyword,
imported with 'import'. Types: built-in ([Link], [Link]) and user-defined.
16. What are Java API packages?
[Link] — auto-imported; Object, String, Math, System, Thread, Integer. [Link] —
ArrayList, HashMap, Scanner, Collections, Arrays. [Link] — File, FileReader,
BufferedReader, PrintWriter. [Link] — Frame, Button, Label (original GUI). [Link] —
JFrame, JButton, JLabel (modern GUI). [Link] — Socket, URL.
17. What is I/O stream?
An I/O stream is an abstraction representing a flow of data between a program and an external
source/destination (file, keyboard, network, memory). Java's [Link] package uses the stream
model for all I/O, treating files, keyboards, and network connections uniformly.
18. What are types of streams?
By data type: Byte Streams (InputStream, OutputStream and subclasses) — raw binary data.
Character Streams (Reader, Writer and subclasses) — Unicode text data. By source: File
streams, Standard I/O streams, Network streams, Memory/Buffer streams.
19. What is file stream?
File streams connect a program to disk files. FileInputStream / FileOutputStream —
byte-based binary file I/O. FileReader / FileWriter — character-based text file I/O. Wrapped
with Buffered versions for efficiency. Always close streams (or use try-with-resources).
20. What is standard I/O stream?
[Link] — InputStream from keyboard. [Link] — PrintStream to console (print,
println, printf). [Link] — PrintStream to console for error messages. Wrap [Link] with
Scanner or BufferedReader for convenient text reading.
5-Mark Questions
1. Explain inheritance with examples.
Inheritance is one of the four pillars of OOP. It allows a subclass to acquire all the fields and
methods of a superclass without rewriting them, establishing an IS-A relationship and enabling
code reuse. The keyword 'extends' is used: class Dog extends Animal. The subclass inherits
all public and protected members of the superclass. Private members are NOT inherited —
they remain hidden, accessible only through public getter/setter methods. The subclass can
add new fields and methods of its own, and it can override inherited methods to provide
specialized behavior. The super keyword is central to inheritance. super() calls the superclass
constructor and must be the very first statement in the subclass constructor. If omitted, Java
automatically inserts super() (calling the no-arg superclass constructor). [Link]()
calls the superclass version of an overridden method from within the subclass. Example —
Single Inheritance: class Animal { String name; void eat() { sysout(name+" eats"); } void
breathe() { sysout(name+" breathes"); } } class Dog extends Animal { void bark() {
sysout(name+" barks"); } } Dog d = new Dog(); [Link](); [Link](); [Link](); — Dog has
access to all Animal methods. Example — Multilevel Inheritance: class Animal { } class Dog
extends Animal { } class GoldenRetriever extends Dog { } GoldenRetriever inherits from both
Dog and Animal through the chain. Benefits of Inheritance: Code reuse — no need to rewrite
common logic. Extensibility — subclasses add or specialize behavior. Consistency — all
subclasses share the superclass interface. Method overriding enables runtime polymorphism.
Important Note: Inheritance creates coupling — changes to the superclass can ripple to all
subclasses. Use inheritance when a true IS-A relationship exists, not just to share code.
2. Describe different types of inheritance.
Java supports multiple forms of inheritance, though multiple inheritance through classes is
prohibited. 1. Single Inheritance: One subclass inherits from exactly one superclass. This is
the simplest and most common form. Creates a clear IS-A relationship with no ambiguity. The
child gets all accessible members of the parent and can extend or specialize them. Example:
class Vehicle { int speed; void move() { } } class Car extends Vehicle { void honk() { } } Car is-a
Vehicle. Car inherits speed and move(), adds honk(). 2. Multilevel Inheritance: A chain of
inheritance where each class extends the class above it. A class at the bottom of the chain
inherits from every class above it. Example: class Animal { } → class Mammal extends Animal
{ } → class Dog extends Mammal { } Dog inherits from both Mammal and Animal. Dog can use
methods from all three levels. 3. Hierarchical Inheritance: Multiple subclasses all inherit from
the same single superclass. The parent has several children, each inheriting common behavior
but adding their own specializations. Example: class Shape { double area() { } } → Circle
extends Shape, Rectangle extends Shape, Triangle extends Shape. All three inherit area() (or
override it) and share Shape's interface. 4. Multiple Inheritance (via Interfaces only): Java
prevents multiple class inheritance (two parents → Diamond Problem). However, a class can
implement multiple interfaces, inheriting multiple type contracts. Example: class Duck
implements Flyable, Swimmable { public void fly() { } public void swim() { } } Duck must
implement both interface contracts. 5. Hybrid Inheritance: A combination of multiple types.
Common in real projects: a class extends one parent and implements multiple interfaces, while
other classes form hierarchical trees around it. Example: class ElectricCar extends Car
implements Electric, Autonomous.
3. Explain visibility modifiers in Java.
Visibility modifiers (access modifiers) are keywords that control which parts of a program can
access a given class, method, or field. Java provides four access levels, from most restrictive
to least restrictive. 1. private (Most Restrictive): A private member is visible only within the
class that declares it. It is completely invisible to all other classes — including subclasses,
even in the same package. This is the cornerstone of encapsulation: hide internal state and
implementation details, expose only what's necessary. Best practice: All instance variables
should be private. Expose them only through carefully designed public getter (accessor) and
setter (mutator) methods that can validate data. Scope: Declaring class only. 2. default
(Package-Private, no keyword): When no access modifier is written, the member has default
access. It is accessible by any class within the same package but completely invisible to
classes in different packages — even if those classes are subclasses. Use case: Internal
helper methods and classes that are implementation details shared within a package but not
part of the public API. Scope: Same package only. 3. protected: Protected members are
accessible within the same package AND by subclasses anywhere (even in different
packages). It bridges the gap between private (too restrictive for subclasses to use) and public
(too open for everything). Protected is the natural modifier for methods and fields that
superclasses intentionally provide for subclasses to use or override, without making them
globally public. Scope: Same package + subclasses in any package. 4. public (Least
Restrictive): Public members are accessible from everywhere — any class, any package, any
project. Public methods form the API of a class: the interface it presents to the world. Public
constructors allow objects to be created from anywhere. Use with care: every public member is
a commitment. Changing it later will break code that uses it. Scope: Everywhere. Practical
Principle (Least Privilege): Always use the most restrictive access modifier that still allows
the program to work correctly. Start with private and only loosen as needed.
4. Discuss interface concept with example.
An interface in Java is a reference type that acts as a pure contract or specification. It answers
the question 'what can this object do?' without specifying how it does it. An interface defines a
set of method signatures (and optionally constants, default methods, and static methods) that
any implementing class must honor. Declaring an Interface: interface Printable { void print();
void preview(); } All declared methods are implicitly public and abstract before Java 8. All
variables are implicitly public, static, and final (constants). Implementing an Interface: A class
uses 'implements': class Document implements Printable { public void print() {
sysout("Printing..."); } public void preview() { sysout("Previewing..."); } } The implementing
class MUST provide a concrete body for every abstract method. If it doesn't, the class must be
declared abstract. Multiple Interface Implementation (Java's Multiple Inheritance): A class
can implement any number of interfaces, gaining all their type contracts: class SmartDevice
implements Connectable, Chargeable, Printable { /* implement all methods */ } This gives Java
most of the benefits of multiple inheritance without the Diamond Problem, because interfaces
don't bring competing implementations. Interface as Type (Polymorphism): Once a class
implements an interface, objects of that class can be referred to by the interface type: Printable
p = new Document(); [Link](); — works for any class implementing Printable. Java 8+
Additions: default methods: interface with a default implementation that classes inherit.
default void log() { sysout("logging"); } static methods: utility methods in the interface. static
void validate(Object o) { } Java 9 added private methods for internal helper logic. Interface vs
Abstract Class: Interface: multiple implementation, no instance state, defines capabilities.
Abstract class: single inheritance, can have state and partial implementation, defines partial
implementation.
5. Explain polymorphism with types.
Polymorphism (Greek for 'many forms') is the OOP principle that allows a single interface or
reference to work with objects of multiple types, each responding in its own way. Type 1 —
Compile-Time Polymorphism (Static Binding / Method Overloading): The method to be
called is determined by the Java compiler at compile time, before the program runs. The
decision is based on the method signature: the number, type, and order of arguments in the
method call. Multiple methods share the same name but differ in their parameter lists. This is
called static binding because the binding between the method call and the method body is
fixed at compile time. Example: 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; } } [Link](5, 3)
→ compiler picks int version. [Link](3.14, 2.71) → picks double version. One name, many
forms. Type 2 — Runtime Polymorphism (Dynamic Binding / Method Overriding): The
method to be called is determined by the JVM at runtime, based on the actual type of the
object the reference points to — not the declared type of the reference variable. A superclass
reference is used to point to different subclass objects, and the correct overridden method is
dispatched dynamically. This requires: (a) A class hierarchy with method overriding. (b)
Upcasting — assigning a subclass object to a superclass reference: Animal a = new Dog();
When [Link]() is called, even though 'a' is declared as Animal, the JVM looks at the actual
object (Dog) and calls Dog's speak(). Example: Animal[] arr = { new Dog(), new Cat(), new
Cow() }; for(Animal a : arr) [Link](); — each call dispatches to the correct subclass method
without any if-else logic. This is the power of polymorphism for building extensible systems.
6. Differentiate method overloading and overriding.
Both involve methods with the same name, but they operate at different levels and serve
different purposes. Method Overloading: Overloading occurs entirely within a single class.
Multiple methods share the same name but must differ in their parameter list (number, type, or
order of parameters). The Java compiler determines which overloaded method to call by
examining the types of arguments at the call site — this decision happens at compile time
(static binding / compile-time polymorphism). Return type alone CANNOT differentiate
overloaded methods — the compiler will report an error. The @Override annotation is NOT
applicable. Overloading improves API usability by letting callers use the same intuitive method
name for related operations regardless of data type (e.g., [Link]() is overloaded for
int, double, String, char[], boolean, Object, etc.). Method Overriding: Overriding occurs
across a class hierarchy — a subclass provides its own implementation of a method declared
in the superclass. The overriding method must have exactly the same name, same parameter
list, and same or covariant return type as the superclass method. The JVM determines which
version to call at runtime (dynamic binding / runtime polymorphism) based on the actual type of
the object. The @Override annotation is strongly recommended — it tells the compiler to verify
that the signature actually matches a superclass method. Access cannot be made more
restrictive in the override. private, static, and final methods cannot be overridden. Key
Differences at a Glance: Where: Overloading — same class; Overriding — parent-child
classes. Binding: Overloading — compile time; Overriding — runtime. Signature: Overloading
— must differ; Overriding — must match. Return type: Overloading — can differ; Overriding —
same or covariant. Access modifier: Overloading — no restriction; Overriding — cannot be
more restrictive. Polymorphism type: Overloading — compile-time; Overriding — runtime.
7. Explain package concept in Java.
A package in Java is a grouping mechanism that organizes related classes and interfaces into
a named namespace, similar to how folders organize files in a file system. Purposes of
Packages: Namespace management: Two classes can share the same name if they belong
to different packages. [Link] and [Link] are both named Date but coexist without
conflict. The fully qualified name ([Link]) uniquely identifies every class.
Access control: Default (package-private) access lets classes in the same package share
internals while hiding those details from external packages, providing a module-like boundary.
Organization: In large projects with hundreds of classes, packages structure them logically
(e.g., [Link], [Link], [Link]), making the codebase navigable.
Reusability: Packages can be compiled into JAR files and distributed as libraries. Declaring a
Package: The package declaration must be the very first line of the .java source file (before
any imports): package [Link]; Importing Packages: import
[Link]; — specific class import. import [Link].*; — wildcard import (all classes in
[Link]). [Link] is automatically imported — no explicit import needed for String, Math,
System, etc. Built-in Package Hierarchy: [Link] (core language), [Link] (utilities), [Link]
(I/O), [Link] and [Link] (GUI), [Link] (networking), [Link] (database). Directory
Structure: Package declaration must match directory structure. Package [Link]
requires the source file to be in com/myapp/util/ directory. Compile from the root: javac
com/myapp/util/[Link]. Run: java [Link].
8. Describe Java API packages (util, awt, swing).
Java's API (Application Programming Interface) is a massive, well-organized collection of
pre-built classes and interfaces. Using built-in packages dramatically accelerates
development. [Link] (Automatically Imported): The most fundamental package — you
cannot write Java without it. Object — root superclass of every class. String, StringBuffer,
StringBuilder — text handling. Math — sqrt, pow, abs, ceil, floor, round, random, PI, E. System
— in, out, err, exit, currentTimeMillis, arraycopy. Thread, Runnable — multithreading
primitives. Integer, Double, Character, Boolean — wrapper classes. Throwable, Exception,
RuntimeException, Error — exception hierarchy. [Link]: Utility toolkit for data structures,
algorithms, and common tasks. Collections Framework: List (ArrayList, LinkedList, Vector), Set
(HashSet, TreeSet, LinkedHashSet), Map (HashMap, TreeMap, LinkedHashMap), Queue
(PriorityQueue, ArrayDeque). Algorithms: [Link](), shuffle(), reverse(), min(), max(),
frequency(). Input: Scanner with nextInt(), nextDouble(), nextLine(), next(). Date/Time: Date,
Calendar, and modern [Link], LocalDateTime. Others: Random (nextInt,
nextDouble, nextBoolean), Arrays (sort, binarySearch, fill, copyOf, toString), Optional.
[Link] (Abstract Window Toolkit): Java's original GUI framework that maps to native OS
components (heavyweight). Frame — top-level window. Panel — sub-container. Button, Label,
TextField, TextArea, Checkbox, Choice, List. Layout managers: FlowLayout, BorderLayout,
GridLayout, CardLayout. Event handling: ActionEvent, MouseEvent, KeyEvent. Graphics for
drawing shapes, text, images. Still used but largely superseded by Swing. [Link]:
Modern, pure-Java GUI (lightweight — rendered entirely by Java, not OS). All components
prefixed with J: JFrame, JPanel, JButton, JLabel, JTextField, JTextArea, JCheckBox,
JRadioButton, JComboBox, JList, JTable, JTree, JSlider, JProgressBar, JScrollPane,
JMenuBar, JMenu, JMenuItem. Supports pluggable look-and-feel for cross-platform
consistency. The preferred GUI toolkit for Java desktop applications.
9. Explain standard I/O streams.
Java provides three standard I/O streams as static fields of the System class. They are
automatically available in every program without any initialization. [Link] — Standard
Input: Type: InputStream (byte-based). Default source: keyboard. Reading raw bytes directly
is awkward, so [Link] is almost always wrapped with a more convenient class. With
Scanner (most common): Scanner sc = new Scanner([Link]); provides nextInt(),
nextDouble(), nextLine(), next(), nextBoolean(). Scanner tokenizes input by whitespace or
newlines. Must call [Link]() after nextInt()/nextDouble() to consume the leftover newline
character before reading a full line. With BufferedReader: BufferedReader br = new
BufferedReader(new InputStreamReader([Link])); [Link]() reads a full line as a
String. More efficient for large input (buffered, fewer system calls).
[Link]([Link]()) for numeric input. [Link] — Standard Output: Type:
PrintStream. Default destination: console/terminal. print(x) — prints x without newline. Works
for all data types. println(x) — prints x followed by a newline. printf(format, args) — C-style
formatted output. Specifiers: %d (int), %f (float/double), %s (String), %c (char), %b (boolean),
%n (newline). Width/precision: %-10s (left-aligned 10 chars), %.2f (2 decimal places).
[Link] can be redirected: [Link](new PrintStream(new
FileOutputStream("[Link]"))); [Link] — Standard Error: Type: PrintStream. Default
destination: console (typically shown in red in IDEs). Purpose: Printing error messages,
warnings, and diagnostic information separately from normal output. This separation matters
because in a shell, standard output (stdout) and standard error (stderr) can be independently
redirected: java App > [Link] 2> [Link]. Normal program output goes to [Link], error messages
to [Link]. Example: [Link]("ERROR: File not found: " + filename);
10. Discuss file streams in Java.
File streams in Java connect a running program to files stored on disk. Java provides a layered
stream architecture: low-level streams handle raw bytes or characters, and wrapper streams
add convenience features like buffering or formatted output. Byte File Streams (for binary
data): FileInputStream reads bytes from a file. FileInputStream fis = new
FileInputStream("[Link]"); int b = [Link](); — reads one byte (-1 at end). int n =
[Link](buffer) — reads into byte array. FileOutputStream writes bytes to a file.
FileOutputStream fos = new FileOutputStream("[Link]"); [Link](65); — writes byte for 'A'.
FileOutputStream("file", true) appends to existing file. Use for: images, audio, video, serialized
Java objects, encrypted data. Character File Streams (for text data): FileReader reads
characters from text files, automatically converting bytes to chars using the platform's default
encoding. FileWriter writes characters to text files. These are better than byte streams for text
because they handle multi-byte character encodings (UTF-8, etc.) correctly. Buffered
Streams (Efficiency Wrappers): Raw file streams make one OS call per character/byte,
which is very slow. Buffered streams read/write a large chunk at once into memory, making
subsequent reads/writes from the buffer — dramatically faster. BufferedReader br = new
BufferedReader(new FileReader("[Link]")); — adds readLine() which reads a full line.
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]")); — adds newLine() for
platform-appropriate line endings. PrintWriter pw = new PrintWriter(new FileWriter("[Link]"));
— adds println() and printf(). Best Practice — Try-with-Resources: try (BufferedReader br =
new BufferedReader(new FileReader("[Link]"))) { String line; while((line = [Link]()) != null) {
process(line); } } The stream is automatically closed when the try block exits, whether normally
or due to an exception. This prevents file handle leaks without explicit finally blocks.
11. Compare compile-time and run-time polymorphism.
These are the two fundamental forms of polymorphism in Java, differing in when and how the
correct method is selected. Compile-Time Polymorphism (Static Binding / Early Binding):
Resolution happens during compilation — the compiler determines which method to call by
examining the method signature (name + parameter types/count) against the available
overloaded methods. Because the binding is determined before the program runs, it is called
static or early binding. Performance is optimal since there is no runtime lookup overhead.
Achieved through method overloading: multiple methods with the same name, different
parameters, in the same class. The compiler picks the correct version based on how the
method is called. Example: print(42) → compiler picks print(int). print("Hello") → picks
print(String). print(3.14) → picks print(double). All resolved at compile time. Limitations: Cannot
adapt to the actual runtime type of objects. Less flexible for extensible designs. Runtime
Polymorphism (Dynamic Binding / Late Binding): Resolution happens during program
execution — the JVM determines which method to call by looking at the actual class of the
object at runtime, not the declared type of the reference. The method is bound late (at
runtime), hence late or dynamic binding. Achieved through method overriding + upcasting: a
superclass reference points to a subclass object. When a method is called on that reference,
the JVM checks the object's actual class and dispatches to the most derived override of that
method (using a virtual method table — vtable). Example: Animal a = new Dog(); [Link](); —
JVM sees Dog object, calls [Link](). Strength: Highly flexible. The same code handles
new subclasses without modification — adding a new Parrot subclass to the hierarchy
automatically works with existing code that iterates Animal references. In Practice: Both forms
often coexist. Compile-time polymorphism handles convenience (same operation on different
input types). Runtime polymorphism handles extensibility (same interface, different
implementations).
12. Explain how interfaces support multiple inheritance.
Java explicitly prohibits a class from extending more than one class. The reason is the
Diamond Problem: if class C extends both A and B, and both A and B define a method with the
same signature, C inherits two competing implementations and the JVM doesn't know which
one to use. This ambiguity can cause unpredictable behavior. Interfaces as the Solution:
Before Java 8, interfaces could only contain abstract method declarations — no
implementations. When a class implements two interfaces that both declare the same method
name, the class must provide its own implementation. There is only one implementation (in the
class), so there is no ambiguity. The Diamond Problem doesn't arise. class FlyingFish
implements Flyable, Swimmable { public void fly() { sysout("gliding"); } public void swim() {
sysout("swimming"); } } FlyingFish gets the types of both Flyable and Swimmable. It IS-A
Flyable AND IS-A Swimmable. Multiple listeners, comparators, and service contracts can all
be implemented simultaneously. Interface Extending Multiple Interfaces: Interfaces
themselves can extend multiple interfaces: interface AmphibiousVehicle extends Flyable,
Swimmable, Drivable { } Any class implementing AmphibiousVehicle must implement all
methods from all three. Java 8 Default Methods and Conflict Resolution: Java 8 added
default methods (methods with implementations) to interfaces. If two interfaces provide default
methods with the same signature and a class implements both, there is a conflict. Java
requires the implementing class to explicitly override and resolve it: class C implements A, B {
public void conflict() { [Link](); } } — programmer explicitly chooses which default to
use, or provides an entirely new implementation. This design gives all the power of multiple
inheritance — multiple type contracts, polymorphic behavior through multiple interface
references — without the ambiguity risk.
13. Discuss the importance of packages.
Packages are not just a convenience feature — they are fundamental to how professional
Java projects are structured, secured, and distributed. 1. Namespace Management and
Conflict Prevention: In any large project or when combining libraries from multiple vendors,
class name collisions are inevitable without namespacing. Without packages, if Library A and
Library B both define a class named Connection, you cannot use both in the same project.
With packages, [Link] and [Link] are completely distinct.
The fully qualified class name (package + class name) uniquely identifies every class in the
Java ecosystem. 2. Encapsulation at the Package Level: Java's access control has four
levels. Default (package-private) access is a powerful tool: it allows classes within the same
package to collaborate closely — accessing each other's internal state and helper methods —
while presenting a clean public API to external packages. This creates a 'module' boundary
that hides internal implementation details from the outside world. 3. Logical Organization and
Maintainability: Real projects have hundreds or thousands of classes. Packages organize
them by responsibility: [Link] (data classes), [Link] (database access),
[Link] (business logic), [Link] (request handling). Any developer joining
the project instantly knows where to find what. This organized structure also makes refactoring
safer — you know which classes belong together. 4. Reusable Library Distribution: A set of
packages can be compiled and archived into a JAR (Java ARchive) file. Other developers add
the JAR to their classpath and import the packages. This is how the entire Java ecosystem
works — Spring, Hibernate, Log4j, JUnit, and millions of other libraries are distributed as JARs.
Maven and Gradle dependency management are built entirely on this package/JAR system. 5.
Security and Stability: Package-private classes that are internal implementation details
cannot be accessed or subclassed by external code. This allows library authors to change
internal implementations in future versions without breaking code that uses the library.
14. Explain creation of user-defined packages.
Creating your own packages in Java is essential for organizing any non-trivial project. Step 1
— Choose the Package Name: By universal convention, package names are all lowercase.
For professional projects, use reverse domain notation to guarantee global uniqueness:
[Link]. For student/personal projects: mypackage,
[Link], etc. The name determines the directory structure. Step 2 —
Declare the Package in the Source File: The package declaration MUST be the very first line
of the .java file (before any import statements): package mypackage; public class MathHelper {
public static int square(int n) { return n*n; } public static boolean isPrime(int n) { if(n<2) return
false; for(int i=2;i*i<=n;i++) if(n%i==0) return false; return true; } } Step 3 — Create Matching
Directory Structure: The source file must reside in a directory that exactly matches the
package name. For package mypackage: save [Link] inside a folder named
mypackage/. For [Link]: create com/myapp/util/ and save the file there. Step 4 —
Compile the Source File: Compile from the parent directory: javac
mypackage/[Link] This creates mypackage/[Link]. Step 5 — Use the
Package in Another Class: In [Link] (in the parent directory): import
[Link]; OR import mypackage.*; public class Main { public static void
main(String[] args) { [Link]([Link](7));
[Link]([Link](17)); } } Step 6 — Compile and Run: javac [Link]
then java Main (JVM searches classpath for the mypackage folder). Sub-packages: package
[Link]; requires com/myapp/util/math/ directory. Sub-packages are independent
namespaces — [Link] does NOT automatically have access to [Link]
members.
15. Describe input and output operations in Java.
Java provides a comprehensive I/O system through the [Link] package, organized around the
concept of streams — channels for data flow. Console Input: Scanner (most common):
Scanner sc = new Scanner([Link]); Reads tokens (whitespace-delimited): [Link](),
[Link](), [Link](), [Link](), [Link](). Must call [Link]() when done.
Important: after calling nextInt() or nextDouble(), call [Link]() once to consume the
leftover newline before reading a String. BufferedReader (efficient): BufferedReader br =
new BufferedReader(new InputStreamReader([Link])); String line = [Link](); int n =
[Link](line); Reads a whole line at once, faster for large inputs. Console Output:
[Link](x) — no newline. [Link](x) — with newline.
[Link]("%-15s %5.2f%n", name, score) — formatted. [Link]() is
identical to printf(). Reading Text Files: try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) { String line; while((line = [Link]()) != null) { process(line); } } Each
readLine() call returns one line (null at end of file). Writing Text Files: try (PrintWriter pw =
new PrintWriter(new FileWriter("[Link]"))) { [Link]("Line 1"); [Link]("Score: %d%n",
95); } Append mode: new FileWriter("[Link]", true) — adds to existing file. Serialization
(Object I/O): Write object: ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]")); [Link](student); Read object: ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("[Link]")); Student s = (Student)
[Link](); Class must implement [Link] interface. Try-with-Resources
(Best Practice): try (resource1; resource2) { ... } — auto-closes all declared resources on exit.
10-Mark Questions (Programs)
1. Single inheritance program.
class Vehicle { String brand,model; int maxSpeed,speed;
Vehicle(String b,String m,int ms){brand=b;model=m;maxSpeed=ms;speed=0;}
void start(){[Link](brand+" "+model+" started.");}
void accelerate(int a){speed=[Link](speed+a,maxSpeed);[Link]("Speed:
"+speed);}
void displayInfo(){[Link](brand+" "+model+" MaxSpeed:"+maxSpeed);}
}
class Car extends Vehicle {
int doors; String fuel;
Car(String b,String m,int ms,int d,String f){super(b,m,ms);doors=d;fuel=f;}
void honk(){[Link](brand+" beeps!");}
@Override void start(){[Link]();[Link]("Seatbelt check done.");}
@Override void displayInfo(){[Link]();[Link]("Doors:"+doors+"
Fuel:"+fuel);}
}
public class SingleInheritance {
public static void main(String[] args){
Car c = new Car("Toyota","Camry",220,4,"Petrol");
[Link]();
[Link]();
[Link](80);
[Link]();
Vehicle v = new Car("Honda","City",200,4,"Petrol"); // upcasting
[Link](); [Link](60);
}
}
2. Multiple inheritance via interfaces.
interface Flyable{void fly(); default void checkWeather(){[Link]("Weather
OK");}}
interface Swimmable{void swim(); void dive(int d);}
class Duck implements Flyable,Swimmable{
String name;
Duck(String n){name=n;}
public void fly(){[Link](name+" flies");}
public void swim(){[Link](name+" swims");}
public void dive(int d){[Link](name+" dives "+d+"m");}
void quack(){[Link](name+": Quack!");}
}
public class MultipleInheritance{
public static void main(String[] args){
Duck d=new Duck("Donald");
[Link](); [Link](); [Link](); [Link](10); [Link]();
Flyable[] flyers={new Duck("Daffy"),new Duck("Huey")};
for(Flyable f:flyers) [Link]();
Swimmable[] swimmers={new Duck("Dewey"),new Duck("Louie")};
for(Swimmable s:swimmers) [Link]();
}
}
3. Method overloading.
public class Overloading{
static double area(double r){return [Link]*r*r;}
static double area(double l,double b){return l*b;}
static double area(int s){return s*s;}
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
static double add(double a,double b){return a+b;}
static String add(String a,String b){return a+b;}
static void print(int n){[Link]("int: "+n);}
static void print(double d){[Link]("double: "+d);}
static void print(String s){[Link]("String: "+s);}
static void print(boolean b){[Link]("bool: "+b);}
public static void main(String[] args){
[Link]("Circle(5): %.4f%n",area(5.0));
[Link]("Rect(4x6): %.2f%n",area(4.0,6.0));
[Link]("Square(7): %.2f%n",area(7));
[Link]("add(3,4)="+add(3,4));
[Link]("add(1,2,3)="+add(1,2,3));
[Link]("add(3.5,2.5)="+add(3.5,2.5));
[Link]("add(Hi,Java)="+add("Hi"," Java"));
print(42); print(3.14); print("Hello"); print(true);
}
}
4. Method overriding.
abstract class Shape{
String name,color;
Shape(String n,String c){name=n;color=c;}
abstract double area();
abstract double perimeter();
void display(){[Link]("%s(%s) Area=%.4f
Perimeter=%.4f%n",name,color,area(),perimeter());}
}
class Circle extends Shape{
double r;
Circle(double r,String c){super("Circle",c);this.r=r;}
double area(){return [Link]*r*r;}
double perimeter(){return 2*[Link]*r;}
}
class Rectangle extends Shape{
double l,b;
Rectangle(double l,double b,String c){super("Rectangle",c);this.l=l;this.b=b;}
double area(){return l*b;}
double perimeter(){return 2*(l+b);}
}
class Triangle extends Shape{
double a,b,c;
Triangle(double a,double b,double c,String
col){super("Triangle",col);this.a=a;this.b=b;this.c=c;}
double area(){double s=(a+b+c)/2;return [Link](s*(s-a)*(s-b)*(s-c));}
double perimeter(){return a+b+c;}
}
public class Overriding{
public static void main(String[] args){
Shape[] shapes={new Circle(7,"Red"),new Rectangle(8,5,"Blue"),new
Triangle(5,12,13,"Green")};
double total=0;
for(Shape s:shapes){[Link]();total+=[Link]();}
[Link]("Total area: %.4f%n",total);
}
}
5. Runtime polymorphism.
class Employee{
String name,id;
double base;
Employee(String n,String i,double b){name=n;id=i;base=b;}
double salary(){return base;}
String role(){return "Employee";}
void display(){[Link]("%-8s %-15s %-12s Rs.%.2f%n",id,role(),name,salary());}
}
class Manager extends Employee{
int team;
Manager(String n,String i,double b,int t){super(n,i,b);team=t;}
double salary(){return base+(base*0.30)+(team*500);}
String role(){return "Manager";}
}
class Developer extends Employee{
int score;
Developer(String n,String i,double b,int s){super(n,i,b);score=s;}
double salary(){return base+(base*0.20)+(base*score*0.02);}
String role(){return "Developer";}
}
class Intern extends Employee{
Intern(String n,String i,double b){super(n,i,b);}
double salary(){return [Link](base,15000);}
String role(){return "Intern";}
}
public class RuntimePolymorphism{
public static void main(String[] args){
Employee[] emp={new Manager("Raj","M01",80000,5),new Developer("Priya","D01",60000,8),
new Intern("Abubakar","I01",12000),new Developer("Ali","D02",65000,9)};
[Link]("%-8s %-15s %-12s %s%n","ID","Role","Name","Salary");
[Link]("-".repeat(55));
double total=0;
for(Employee e:emp){[Link]();total+=[Link]();}
[Link]("Total Payroll: Rs.%.2f%n",total);
}
}
6. Package demo (simulated).
// Simulating package classes in one file
class BankAccount{
protected String accNo,holder;
protected double balance;
BankAccount(String a,String h,double b){accNo=a;holder=h;balance=b;}
void deposit(double amt){balance+=amt;[Link]("Deposited %.2f | Balance:
%.2f%n",amt,balance);}
boolean withdraw(double amt){
if(balance>=amt){balance-=amt;[Link]("Withdrawn %.2f | Balance:
%.2f%n",amt,balance);return true;}
[Link]("Insufficient balance.");return false;
}
void show(){[Link](accNo+" | "+holder+" | Rs."+balance);}
}
class SavingsAccount extends BankAccount{
double rate,minBal;
SavingsAccount(String a,String h,double b,double r){super(a,h,b);rate=r;minBal=1000;}
@Override boolean withdraw(double amt){
if(balance-amt<minBal){[Link]("Min balance Rs."+minBal+" required.");return
false;}
return [Link](amt);
}
void addInterest(){double i=balance*rate/100;balance+=i;[Link]("Interest
+%.2f | Balance: %.2f%n",i,balance);}
}
public class PackageDemo{
public static void main(String[] args){
SavingsAccount sa=new SavingsAccount("S001","Abubakar",25000,4.5);
[Link](); [Link](5000); [Link](10000); [Link](20000); [Link]();
[Link]();
BankAccount[] all={sa,new BankAccount("C001","Alice",15000)};
[Link]("\n--- All Accounts ---");
double total=0;
for(BankAccount a:all){[Link]();total+=[Link];}
[Link]("Total: Rs.%.2f%n",total);
}
}
7. Standard I/O streams.
import [Link];
public class StandardIO{
public static void main(String[] args){
// [Link] formatting
[Link]("=== [Link] Demo ===");
[Link]("%-10s | %5s | %7s | %s%n","Name","Roll","Average","Grade");
[Link]("-".repeat(38));
String[][] data={{"Abubakar","101","88.00","A"},{"Alice","102","92.50","O"},{"Bob","103"
,"68.00","B"}};
for(String[] r:data) [Link]("%-10s | %5s | %7s | %s%n",r[0],r[1],r[2],r[3]);
[Link]("[Link]: This is an error message");
// [Link] with Scanner
Scanner sc=new Scanner([Link]);
[Link]("\nEnter your name: ");
String name=[Link]();
[Link]("Enter your age: ");
int age=[Link]();
[Link]("Enter GPA: ");
double gpa=[Link]();
[Link]("\n--- Profile ---");
[Link]("Name : "+name);
[Link]("Age : "+age);
[Link]("GPA : %.2f%n",gpa);
[Link]("Status: "+(gpa>=6?"Good Standing":"Warning"));
[Link]();
}
}
8. File handling with streams.
import [Link].*;
public class FileHandling{
static final String FILE="/tmp/[Link]";
static void write() throws IOException{
try(BufferedWriter bw=new BufferedWriter(new FileWriter(FILE))){
[Link]("BCA 2nd Semester Report"); [Link]();
String[][] data={{"101","Abubakar","88","92","85"},{"102","Alice","95","90","93"},{"103"
,"Bob","72","68","75"}};
for(String[] r:data){[Link]([Link](",",r));[Link]();}
[Link]("Written "+[Link]+" records.");
}
}
static void read() throws IOException{
try(BufferedReader br=new BufferedReader(new FileReader(FILE))){
[Link]("\n--- File Contents ---");
String line; int lno=0;
while((line=[Link]())!=null){
lno++;
if(lno==1){[Link](line);continue;}
String[] p=[Link](",");
double
avg=([Link](p[2])+[Link](p[3])+[Link](p[4]))/3;
[Link]("%-10s Avg: %.2f Grade: %s%n",p[1],avg,avg>=80?"A":avg>=60?"B":"C");
}
}
}
static void append() throws IOException{
try(FileWriter fw=new FileWriter("/tmp/[Link]",true)){
[Link]("[LOG] New entry\n");
}
}
public static void main(String[] args){
try{write();read();append();[Link]("All file ops done.");}
catch(IOException e){[Link]("Error: "+[Link]());}
}
}
9. ArrayList demonstration.
import [Link].*;
public class ArrayListDemo{
public static void main(String[] args){
ArrayList<String> list=new ArrayList<>();
[Link]("Mango"); [Link]("Apple"); [Link]("Banana"); [Link]("Orange");
[Link]("Apple");
[Link]("List : "+list);
[Link]("Size : "+[Link]());
[Link]("get(1) : "+[Link](1));
[Link]("contains: "+[Link]("Banana"));
[Link]("indexOf : "+[Link]("Apple"));
[Link](2,"Grapes"); [Link]("After set: "+list);
[Link]("Orange"); [Link]("After remove: "+list);
[Link](1,"Pineapple"); [Link]("After add(1): "+list);
[Link](list); [Link]("Sorted : "+list);
[Link](list); [Link]("Reversed: "+list);
[Link]("for-each: ");
for(String f:list) [Link](f+" ");
[Link]();
Iterator<String> it=[Link]();
while([Link]()){String f=[Link]();if([Link]("P"))[Link]();}
[Link]("After remove P*: "+list);
[Link]("Min: "+[Link](list)+" Max: "+[Link](list));
[Link](); [Link]("After clear: "+list+" isEmpty: "+[Link]());
}
}
10. Inheritance vs interfaces analysis.
// Inheritance: IS-A | Interface: CAN-DO
interface Trainable{void train(String cmd);default void
basicCmds(){[Link]("sit,stay,come");}}
interface Swimmable{void swim();}
class Animal{String name;int age;
Animal(String n,int a){name=n;age=a;}
void breathe(){[Link](name+" breathes");}
void eat(String f){[Link](name+" eats "+f);}
}
class Dog extends Animal{
String breed;
Dog(String n,int a,String b){super(n,a);breed=b;}
void bark(){[Link](name+": Woof!");}
@Override public String toString(){return name+"("+breed+","+age+"yr)";}
}
class TrainedDog extends Dog implements Trainable,Swimmable{
TrainedDog(String n,int a,String b){super(n,a,b);}
public void train(String c){[Link](name+" trained: "+c);}
public void swim(){[Link](name+" swims!");}
}
public class InheritanceVsInterface{
public static void main(String[] args){
TrainedDog td=new TrainedDog("Max",4,"German Shepherd");
[Link](); // from Animal
[Link]("kibble"); // from Animal
[Link](); // from Dog
[Link]("roll over"); // from Trainable
[Link](); // default from Trainable
[Link](); // from Swimmable
[Link]("Dog IS-A Animal: "+(td instanceof Animal));
[Link]("Dog IS-A Trainable: "+(td instanceof Trainable));
[Link]("Dog IS-A Swimmable: "+(td instanceof Swimmable));
Trainable t=td; [Link]("fetch"); // interface reference
Swimmable s=td; [Link](); // interface reference
Animal a=td; [Link](); // superclass reference
}
}
UNIT – III
Event Handling, GUI, Layout Managers, Applets, Strings
2-Mark Questions
1. What is event handling in Java?
Event handling is the mechanism that controls what happens when a user interacts with GUI
components (button click, key press, mouse move). Java uses the Delegation Event Model —
events are generated by the source component and delegated to separate listener objects that
contain the handling logic.
2. What is an event?
An event is an object describing a state change in a GUI source component (button clicked,
key pressed, mouse moved). Created automatically by the JVM on user interaction. All event
classes are in [Link] and extend [Link]. Contains source, type, and
relevant data.
3. Define event listener.
An event listener is an interface with callback methods for handling specific events. A class
implements the interface, registers with the source using addXxxListener(), and the source
calls the callback automatically when the event occurs. Example: ActionListener has
actionPerformed(ActionEvent e).
4. What is delegation event model?
A model separating event generation from handling. Event Source (component) generates an
event object and notifies all registered Event Listeners (handler objects implementing listener
interfaces). The source delegates responsibility for response to the listener. Components:
Source → Event Object → Listener.
5. What is a GUI?
GUI (Graphical User Interface) is a visual interface using windows, buttons, text fields, menus,
and icons rather than text commands. Java provides AWT (original, heavyweight, uses native
OS components) and Swing (modern, lightweight, pure Java rendering, preferred).
6. What is a Frame in Java?
A Frame ([Link]) is the top-level AWT window with title bar, border, and
close/minimize/maximize buttons. It is the main container. The Swing equivalent JFrame adds
default close operations and a content pane. Created with: new Frame("Title"); setSize();
setVisible(true);
7. What is a Panel?
A Panel ([Link]) is an intermediate container placed inside a Frame. It cannot exist
independently. Has its own layout manager. Used to group components logically. The Swing
equivalent is JPanel, which supports custom painting and is more feature-rich.
8. What is a layout manager?
A layout manager automatically controls the size and position of components in a container,
adapting when the window is resized. Without one (null layout), programmer manually calls
setBounds(). Built-in managers: FlowLayout, BorderLayout, GridLayout, CardLayout,
GridBagLayout.
9. Name different layout managers.
1. FlowLayout — left-to-right, wraps rows, default for JPanel. 2. BorderLayout — 5 regions
(N,S,E,W,Center), default for JFrame. 3. GridLayout — equal-sized cells in grid. 4.
CardLayout — one panel visible at a time. 5. GridBagLayout — most flexible, components
span rows/cols. 6. BoxLayout — row or column arrangement.
10. What is FlowLayout?
FlowLayout places components left-to-right in rows. When a row fills, components wrap to the
next row. Components keep their preferred sizes. Default for JPanel. Alignment: LEFT,
CENTER (default), RIGHT. Constructor: new FlowLayout([Link], hgap, vgap).
11. What is GridLayout?
GridLayout divides the container into a uniform grid of equal-sized cells. Components added
left-to-right, top-to-bottom. All components stretched to fill equal cell size. Constructor: new
GridLayout(rows, cols, hgap, vgap). rows=0 means auto-calculated. Best for calculators,
keypads.
12. What is BorderLayout?
BorderLayout divides into 5 named regions: NORTH, SOUTH, EAST, WEST, CENTER. One
component per region. CENTER gets all remaining space. NORTH/SOUTH take full width.
EAST/WEST take full height. Default for JFrame. add(comp, [Link]).
13. What is a button in GUI?
Button (AWT) / JButton (Swing) is a clickable component triggering an ActionEvent on click.
Displays text, icon, or both. Register: [Link](listener). In actionPerformed,
[Link]() identifies which button was clicked. [Link]() returns the button
label.
14. What is a checkbox?
Checkbox (AWT) / JCheckBox (Swing) is an independent on/off toggle — multiple can be
selected simultaneously. Fires ItemEvent on state change. Listener: ItemListener →
itemStateChanged(). State read with isSelected() (Swing) or getState() (AWT). Used for
multiple-choice selections.
15. What is a radio button?
JRadioButton (Swing) is for mutually exclusive choices — only one in a ButtonGroup can be
selected. Group: ButtonGroup bg = new ButtonGroup(); [Link](rb1); [Link](rb2); Selecting
one auto-deselects others. Fires ItemEvent and ActionEvent. Used for gender, size, payment
method selections.
16. What is a label?
Label (AWT) / JLabel (Swing) is a non-interactive display component for text or images. Does
not generate events. JLabel supports HTML markup: new JLabel("Bold"). Created: new
JLabel("Name:"). Methods: getText(), setText(), setFont(), setForeground().
17. What is a text field?
TextField (AWT) / JTextField (Swing) is a single-line text input. Width set by column count.
getText() reads content, setText() sets it. Fires ActionEvent on Enter key. For multi-line input
use JTextArea. For password masking use JPasswordField (getPassword() returns char[]).
18. What is an applet?
An applet is a Java program that runs inside a web browser or appletviewer. It extends
[Link] or [Link]. Has no main() — lifecycle managed by the browser
through init(), start(), stop(), destroy(). Embedded via HTML <applet> tag. Now deprecated
and removed from modern browsers.
19. What is applet life cycle?
Four lifecycle methods called by browser/appletviewer: 1. init() — once, on load, initialization.
2. start() — each activation (after init + each revisit). 3. stop() — each deactivation (tab switch,
minimize). 4. destroy() — once, on unload, final cleanup. paint(Graphics g) renders the
display.
20. What is string immutability?
Once a String object is created, its content cannot be changed. Any modification creates a new
String object. Benefits: Thread safety (safe to share across threads), String Pool optimization
(identical literals share one object), Security (class names/passwords can't be altered),
hashCode caching (efficient HashMap key).
5-Mark Questions
1. Explain event handling mechanism in Java.
Event handling in Java is the process of detecting and responding to user interactions with GUI
components. Java uses the Delegation Event Model, which cleanly separates the component
code from the event response code. Three Participants: 1. Event Source: Any AWT/Swing
component capable of generating events — JButton, JTextField, JCheckBox, JComboBox,
JFrame, etc. The source component maintains an internal list of registered listener objects.
When a user action occurs, the source automatically creates an event object and calls the
corresponding callback method on every registered listener. 2. Event Object: An instance of a
class from [Link] that encapsulates all information about what happened. ActionEvent
contains the source component and action command. MouseEvent contains x/y coordinates,
button identifier, and click count. KeyEvent contains the key code and key character. All
extend [Link]. 3. Event Listener: An object that implements a listener interface.
The interface defines one or more abstract callback methods. When the event fires, the source
calls these methods on all registered listeners. Step-by-Step Implementation: Step 1: Create
the component: JButton btn = new JButton("Submit"); Step 2: Implement the listener: class
Handler implements ActionListener { public void actionPerformed(ActionEvent e) { /* logic here
*/ } } Step 3: Register the listener: [Link](new Handler()); Step 4: Add
component to container and display. Handling Multiple Sources: One listener can handle
multiple components. Use [Link]() to identify which component fired the event:
if([Link]() == btn1) ... else if([Link]() == btn2) ... Modern Approaches:
Anonymous inner class: [Link](new ActionListener() { public void
actionPerformed(ActionEvent e) { ... } }); Lambda (Java 8+): [Link](e ->
handleSubmit()); — concise, keeps handler near declaration. The Delegation Model ensures
clean separation — changing the event handler doesn't require modifying the component, and
the same handler logic can be reused across different components.
2. Describe delegation event model.
The Delegation Event Model is Java's standard framework for event handling in AWT and
Swing, introduced in Java 1.1. It replaced the older, inflexible inheritance-based model. Core
Principle: The component that generates an event (the source) does NOT handle the event
itself. Instead, it delegates that responsibility to one or more separate listener objects. This
separation of concerns is the heart of the model — components are responsible only for
generating events, listeners are responsible only for responding. Detailed Roles: Event
Source: Any GUI component. It maintains a list (EventListenerList) of all registered listeners.
When a user interacts, the source: creates the appropriate event object, iterates its listener list,
calls the corresponding callback method on each listener. Registration:
[Link](listener); Deregistration: [Link](listener);
Event Object: Extends [Link]. Carries details: getSource() returns the
component. For ActionEvent: getActionCommand() returns button label or text field content.
For MouseEvent: getX(), getY(), getButton(), getClickCount(). For KeyEvent: getKeyCode()
(virtual key), getKeyChar() (Unicode char), isShiftDown(), isControlDown(), isAltDown(). For
ItemEvent: getStateChange() returns SELECTED or DESELECTED. Event Listener:
Implements one of the listener interfaces in [Link]. Key interfaces: ActionListener (1
method), MouseListener (5 methods), KeyListener (3 methods), ItemListener (1 method),
WindowListener (7 methods). The implementing class must provide bodies for all methods in
the interface (or extend an Adapter class for multi-method interfaces). Advantages Over Old
Model: Clean separation makes GUI code more maintainable and testable. A listener can
register with multiple sources. Multiple listeners can respond to the same event. Adding event
handling doesn't modify the component class. Event processing can be delegated to
specialized objects (command pattern).
3. Explain different types of events.
Java events are organized by the type of user interaction they represent. Each type has a
dedicated class and listener interface in [Link]. 1. ActionEvent: The most commonly
used event type. Generated when: a JButton is clicked, Enter is pressed in a JTextField, a
JMenuItem is selected. Listener: ActionListener with one method: void
actionPerformed(ActionEvent e). Useful method: [Link]() returns the button
label or the text field content. [Link]() returns the component. Register:
[Link](this); 2. MouseEvent: Generated by mouse interactions on any
component. MouseListener has 5 methods: mouseClicked (quick press+release at same
point), mousePressed (button pushed down), mouseReleased (button lifted), mouseEntered
(cursor enters component boundary), mouseExited (cursor leaves). MouseMotionListener
adds 2: mouseMoved (cursor moves, no button), mouseDragged (cursor moves with button
held). Key data: getX(), getY() (cursor position), getButton()
(BUTTON1/BUTTON2/BUTTON3), getClickCount() (1 or 2 for double-click). MouseAdapter
provides empty implementations — extend it and override only what you need. 3. KeyEvent:
Generated when a focused component receives keyboard input. KeyListener has 3 methods:
keyPressed (any key held down — fires repeatedly if held), keyReleased (key lifted), keyTyped
(Unicode character generated — does NOT fire for non-printable keys like arrows, function
keys). Key data: getKeyCode() (virtual key constant like VK_ENTER, VK_ESCAPE, VK_UP),
getKeyChar() (the Unicode character), [Link](code) (human-readable name).
4. ItemEvent: Generated by selection controls when their state changes. Sources:
JCheckBox, JRadioButton, JComboBox. Listener: ItemListener with void
itemStateChanged(ItemEvent e). Key method: [Link]() returns
[Link] or [Link]. [Link]() returns the affected item. 5.
WindowEvent: Generated by window lifecycle actions. WindowListener has 7 methods. Most
important: windowClosing (called when user clicks X — use setDefaultCloseOperation or
dispose() here), windowOpened, windowClosed. WindowAdapter provides empty
implementations for convenient extension.
4. Explain layout managers with examples.
Layout managers automatically control component placement and sizing within containers,
adapting to window resizes. 1. FlowLayout: Places components sequentially left-to-right in a
row. When the row is full, wraps to the next row — like text in a word processor. Components
keep their preferred sizes. Default layout for JPanel. Alignment options: LEFT, CENTER
(default), RIGHT. Constructor: new FlowLayout([Link], 10, 5) — centered,
10px horizontal gap, 5px vertical gap. Use case: Toolbars, dialog button rows, any loose
collection of same-sized components. [Link](new FlowLayout([Link]));
[Link](new JButton("A")); [Link](new JButton("B")); 2. BorderLayout: Divides the
container into five named regions. NORTH and SOUTH span full width (preferred height).
EAST and WEST span full height minus NORTH/SOUTH (preferred width). CENTER fills all
remaining space. Unused regions give their space to CENTER. Default layout for JFrame's
content pane. add(new JMenuBar(), [Link]); add(mainPanel,
[Link]); add(statusBar, [Link]); Use case: Standard
application window with header, footer, sidebar, main content. 3. GridLayout: Divides
container into a rectangular grid of equal cells. All cells identical size. Components stretched to
fill cells. Added left-to-right, top-to-bottom. new GridLayout(rows, cols, hgap, vgap). rows=0
means auto-calculated. Use case: Calculator buttons, phone keypads, grid-based games, any
uniform grid. [Link](new GridLayout(4, 3, 2, 2)); for(int i=0;i<12;i++) [Link](new
JButton([Link](i))); 4. GridBagLayout: The most powerful and complex layout
manager. Each component has a GridBagConstraints object specifying its grid position (gridx,
gridy), span (gridwidth, gridheight), resize behavior (fill), weight (weightx, weighty), and anchor.
Use case: Complex forms where fields have different widths and must align precisely. Nesting
Layouts: Real UIs combine layouts: JFrame (BorderLayout) → NORTH: JPanel (FlowLayout)
with toolbar buttons → CENTER: JPanel (GridLayout) with form fields → SOUTH: JPanel
(FlowLayout) with OK/Cancel buttons.
5. Compare FlowLayout, GridLayout and BorderLayout.
These three are the most widely used layout managers. Understanding their differences helps
choose the right one for each part of a GUI. FlowLayout: Arrangement: Places components
sequentially left-to-right. When a row fills up (based on container width), wraps to the next row
— exactly like words in a paragraph. Sizing: Every component keeps its own preferred size.
No stretching occurs. Dynamic behavior: Adding or removing components automatically
reflows the layout. Window resizing can cause components to jump rows. Configuration:
FlowLayout(alignment, hGap, vGap). Alignment sets per-row justification. Default for: JPanel
and Panel (AWT). Ideal for: Button bars, toolbars, navigation links, any loose grouping where
natural wrapping is acceptable. Limitation: Unpredictable layout with many components or
window resizing. GridLayout: Arrangement: Creates a fixed rows × columns grid.
Components fill cells strictly left-to-right, top-to-bottom, one per cell. Sizing: All cells are
identical size. Every component is stretched to fill its cell regardless of preferred size. All
components appear the same size. Dynamic behavior: Fixed structure — no wrapping.
Window resize scales all cells proportionally. Configuration: GridLayout(rows, cols, hGap,
vGap). Setting rows=0 lets Java calculate rows. Default for: Nothing (must be set explicitly).
Ideal for: Calculators, numeric keypads, calendar grids, color palettes, anything needing
uniform equal components. Limitation: Forces all components to same size — inappropriate
when components should have different sizes. BorderLayout: Arrangement: Divides into
exactly 5 named semantic regions. NORTH/SOUTH span full width. EAST/WEST span
remaining height. CENTER fills all leftover space. Sizing: CENTER is stretched both ways to
fill remaining space. Others sized to preferred in one dimension. Structure: Most intentional of
the three — each region has a semantic meaning. Configuration: add(component,
[Link]); etc. Unused regions are collapsed. Default for: JFrame content pane.
Ideal for: Standard application layout — menu bar (NORTH), status bar (SOUTH), navigation
panel (WEST), tools (EAST), main content (CENTER).
6. Describe GUI components in Java.
Java provides two layers of GUI components: AWT ([Link]) — the original, heavyweight
components using native OS rendering, and Swing ([Link]) — modern, lightweight,
pure-Java components that render consistently across all platforms. Swing is preferred.
Top-Level Container Components: JFrame — the main application window. Has title bar,
border, system buttons. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). Content
added to getContentPane() (or directly in modern Java). JDialog — modal or non-modal
pop-up dialog for messages, prompts, and sub-forms. JApplet — applet container
(deprecated). Intermediate Containers: JPanel — general-purpose container. Can have any
layout manager. Used to group related components. Supports custom painting by overriding
paintComponent(Graphics g). JScrollPane — wraps a component (JTextArea, JList, JTable) to
add scroll bars automatically. JTabbedPane — multiple panels selectable via tabs. JSplitPane
— splits container into two resizable areas. Basic Controls: JLabel — static text or image
display. Non-interactive. JButton — push button. Fires ActionEvent on click. JToggleButton —
stays pressed/unpressed. Also fires ActionEvent. JTextField — single-line text input. Fires
ActionEvent on Enter. JTextArea — multi-line text display/input. Usually wrapped in
JScrollPane. JPasswordField — single-line input with character masking. Selection Controls:
JCheckBox — independent on/off toggle. ItemEvent/ActionEvent. JRadioButton — mutually
exclusive choice in a ButtonGroup. JComboBox<T> — drop-down list. ItemEvent on selection.
JList<T> — scrollable list, single or multiple selection. JSlider — numeric value via sliding.
ChangeEvent. JSpinner — incremental numeric input. Menu System: JMenuBar → JMenu →
JMenuItem (and JCheckBoxMenuItem, JRadioButtonMenuItem, JSeparator). Display
Components: JProgressBar, JToolBar, JTable (tabular data), JTree (hierarchical data).
7. Explain usage of buttons, labels and text fields.
JButton, JLabel, and JTextField are the three most fundamental Swing components — virtually
every GUI form uses all three. JButton: A JButton is a push button that the user clicks to
trigger an action. It fires an ActionEvent to all registered ActionListeners when clicked.
Creation: JButton btn = new JButton("Submit"); or with icon: new JButton(new
ImageIcon("[Link]")); Key methods: setText("text"), getText(), setEnabled(false) (grays out),
setToolTipText("Click to submit"), setMnemonic(KeyEvent.VK_S) (Alt+S shortcut),
setBackground([Link]), setForeground([Link]). Event: [Link](e
-> { String cmd = [Link](); /* "Submit" */ process(); }); Multiple buttons can
share one listener — distinguish using [Link]() == btn1 or by getActionCommand().
JLabel: A JLabel is a read-only display component. It does not fire events or accept user
input. Used to describe other components ("Enter Name:") or display results. Creation: JLabel
lbl = new JLabel("Username:"); or JLabel lbl = new JLabel("OK", [Link]); HTML
support: new JLabel("<html><font color=red><b>Error!</b></font></html>") — enables rich
text. Key methods: setText("new text"), getText(), setFont(new Font("Arial", [Link], 14)),
setForeground([Link]), setHorizontalAlignment([Link]), setIcon(icon). Common
use: Display validation feedback ("Password too short"), show computed results, describe
adjacent text fields. JTextField: A JTextField allows the user to type and edit a single line of
text. Creation: JTextField tf = new JTextField(20); — 20 character columns wide. Key
methods: getText() — get current text, setText("default") — set text, setEditable(false) — make
read-only (like a result display), setColumns(n) — change width,
setHorizontalAlignment([Link]). Events: [Link](e ->
process([Link]())); — fires on Enter key. [Link]().addDocumentListener(dl) —
fires on every character change, useful for real-time validation. Related: JPasswordField —
extends JTextField, masks chars with ●. Use getPassword() (returns char[], not String) for
security. Typical Form Pattern: JPanel with GridLayout(n, 2): column 1 = JLabels, column 2 =
JTextFields. Followed by a FlowLayout panel with Submit and Clear buttons.
8. Explain checkboxes and radio buttons.
Checkboxes and radio buttons are selection controls that allow users to make choices,
differing in whether choices are independent or mutually exclusive. JCheckBox —
Independent Multi-Selection: A JCheckBox represents a binary on/off toggle. Multiple
checkboxes operate completely independently — any number can be selected simultaneously.
This makes them appropriate for options where multiple choices apply simultaneously (e.g.,
interests: Java, Python, C++; features: Enable sound, Show notifications, Auto-save).
Creation: JCheckBox cb = new JCheckBox("Enable Notifications"); or pre-selected: new
JCheckBox("Remember Me", true); State reading: [Link]() returns true if checked.
State setting: [Link](true); or [Link](false); Events: [Link](e -> {
if([Link]() == [Link]) onEnable(); else onDisable(); }); Also
supports ActionListener (fires on every toggle regardless of direction). Multiple checkboxes
can share one ItemListener — use [Link]() or cast [Link]() to identify which.
JRadioButton — Mutually Exclusive Selection: A JRadioButton on its own behaves like a
JCheckBox. The mutual exclusion behavior requires grouping them in a ButtonGroup.
ButtonGroup ensures that selecting one radio button automatically deselects all others in the
same group. Each set of exclusive options needs its own ButtonGroup. Creation:
JRadioButton rbMale = new JRadioButton("Male"); JRadioButton rbFemale = new
JRadioButton("Female"); Grouping: ButtonGroup genderGroup = new ButtonGroup();
[Link](rbMale); [Link](rbFemale); [Link](true); — sets
default. State reading: [Link]() — true/false. Or: ButtonModel selected =
[Link](); [Link](); Events: Same as JCheckBox —
addItemListener or addActionListener. Best Practice: Group related checkboxes or radio
buttons inside a JPanel with a titled border for visual clarity:
[Link]([Link]("Gender")); — creates a box with a title
around the group.
9. Discuss applet and its features.
An applet is a specialized Java program designed to run inside a web browser or the
appletviewer utility (bundled with JDK). Applets were Java's answer to creating interactive,
multimedia content in web pages during the 1990s and early 2000s, before JavaScript and
HTML5 became capable. Key Features: 1. Browser-Embedded Execution: Applets are
embedded in HTML web pages using the <applet> tag or later the <object> tag. When a
browser loads the page, it downloads the applet's .class files, launches the Java Plugin, and
runs the applet in a dedicated area on the page. Parameters can be passed from HTML to the
applet via <param> tags and read with getParameter("name"). 2. Browser-Managed
Lifecycle: Unlike standalone applications that start at main() and end when main() returns, the
browser controls an applet's lifecycle through four standardized methods: init(), start(), stop(),
destroy(). The applet does not control when it starts, pauses, or terminates. 3. Graphical
Output via paint(): Applets render graphics by overriding paint(Graphics g). The Graphics
object provides methods to draw: drawString(), drawLine(), drawRect(), drawOval(), fillRect(),
drawImage(), setColor(), setFont(). paint() is called by the browser whenever the applet needs
to redraw (on load, window expose, resize, or repaint() call). 4. GUI Capability: Applets extend
Applet or JApplet — both are Containers. They can contain any AWT or Swing components,
respond to events, and behave like mini-applications within the browser window. 5. Security
Sandbox: Unsigned applets run in a strictly controlled sandbox. They cannot: read or write
local files, make network connections to servers other than the originating host, run local
system commands, or access sensitive system resources. Signed applets can request
elevated permissions. 6. Current Status — Deprecated: Applets are now obsolete. Oracle
deprecated the Applet API in Java 9, removed it from the JDK in Java 11. All major browsers
dropped Java Plugin support. Modern alternatives: JavaFX for rich desktop apps,
HTML5/JavaScript/WebAssembly for browser-based interactivity.
10. Explain applet life cycle methods.
The applet lifecycle defines the precise sequence and conditions under which the browser or
appletviewer calls specific methods to manage the applet from loading to termination. 1. init()
— One-Time Initialization: Called exactly once when the applet is first loaded by the browser.
It is the applet's initialization phase — equivalent to a constructor or the main() method in a
standalone application. What to do here: Create and add GUI components, initialize instance
variables, read parameters from HTML (getParameter()), load images and audio, establish
initial state. What NOT to do: Don't perform operations that need to be repeated each time the
applet becomes visible (those go in start()). Example: public void init() {
setBackground([Link]); add(new Button("Start")); score = 0; name =
getParameter("playerName"); } 2. start() — Begin/Resume Activity: Called immediately after
init() completes, and then again every time the applet becomes visible again (user navigates
back to the tab, restores a minimized window, scrolls the applet into view). What to do here:
Start or resume ongoing activities — animation threads, timers, background processing,
streaming updates. Note: Can be called multiple times. Each call to stop() is typically paired
with a future call to start(). Example: public void start() { timer = new Timer(50, this);
[Link](); } 3. stop() — Pause Activity: Called every time the applet becomes invisible —
user navigates to another page, minimizes the browser, switches tabs, or scrolls the applet out
of view. What to do here: Pause resource-intensive activities to conserve CPU and memory
while not visible. Stop animation threads, pause timers, suspend network polling. Note: The
applet object is NOT destroyed — it resumes from the same state when start() is called again.
Example: public void stop() { if(timer != null) [Link](); } 4. destroy() — Final Cleanup:
Called once when the applet is permanently unloaded — browser tab closed, page navigated
away for the last time. Called after the final stop(). What to do here: Release all resources —
close network connections, free memory-intensive objects, save any persistent state,
deregister listeners. Example: public void destroy() { if(connection != null) [Link](); }
5. paint(Graphics g) — Rendering: Not a lifecycle method but closely related. Called
whenever the applet's display needs to be redrawn — after start(), after a window expose
event, after resize, or when repaint() is called by animation code. Override to draw graphics.
11. Compare applet and application.
Java can run programs in two modes: as standalone applications and as browser-embedded
applets. They differ significantly in entry point, environment, security, and lifecycle.
Standalone Application: Entry point: The JVM looks for public static void main(String[] args)
and begins execution there. All execution flow is controlled by the programmer. How to run:
From command line — java MyApp, or by double-clicking a JAR file. Environment: Runs as an
independent process on the user's local machine. Has its own JVM process, its own memory
space. System access: Full unrestricted access to the filesystem, network, system properties,
native libraries, and OS commands (subject to OS-level permissions, not JVM-level
sandboxing). UI: Can be purely console-based, or use any GUI framework (AWT, Swing,
JavaFX). JFrame is the top-level window for GUI applications. Lifecycle:
Programmer-controlled. The program runs until main() returns, [Link]() is called, or an
unhandled exception terminates it. Distribution: .class files or .jar archive, optionally with an
installer. Runs on any JVM-equipped machine. Status: Fully supported and the standard way
to deploy Java programs. Applet: Entry point: None — no main(). The browser/appletviewer
controls execution through the lifecycle methods: init() → start() → (stop ↔ start cycle) →
destroy(). How to run: Browser downloads .class files via HTTP, launches Java Plugin to run
applet within the page. Environment: Runs inside the browser's JVM sandbox, embedded in an
HTML page. System access: Heavily restricted sandbox. Cannot access local files, cannot
connect to arbitrary network hosts, cannot run system commands. UI: Always graphical —
applet is a Container (extends Applet/JApplet) and renders in a fixed rectangular area on the
page. Lifecycle: Browser-controlled. Browser calls init/start/stop/destroy at its discretion.
Distribution: Hosted on a web server. Browser fetches on demand. Status: Deprecated since
Java 9, removed from Java 11, unsupported by all modern browsers. Do not use for new
development.
12. Explain string operations in Java.
Java's String class provides a comprehensive API for working with text. Since String objects
are immutable, all these methods return new String objects. Measurement Methods: length()
— count of characters: "Hello World".length() → 11. isEmpty() — true if length is 0: "".isEmpty()
→ true. isBlank() — true if empty or only whitespace (Java 11+). Character Access:
charAt(int index) — character at position (0-based): "Java".charAt(0) → 'J'. toCharArray() —
converts String to char[]. Search Methods: indexOf(str) — index of first occurrence, -1 if not
found: "Hello Java".indexOf("Java") → 6. lastIndexOf(str) — index of last occurrence.
contains(str) — true if string contains the specified substring. startsWith(prefix) — true if string
begins with prefix. endsWith(suffix) — true if string ends with suffix. Transformation
Methods: toUpperCase() — "hello" → "HELLO". toLowerCase() — "JAVA" → "java". trim() —
removes leading/trailing whitespace: " hi " → "hi". strip() — Unicode-aware trim (Java 11+).
stripLeading(), stripTrailing(). replace(old, new) — replaces all occurrences:
"aabba".replace("a","X") → "XXbbX". replaceAll(regex, str) — regex-based replacement.
substring(start) — from index to end. substring(start, end) — from start to end-1. Splitting and
Combining: split(regex) — splits into array: "a,b,c".split(",") → ["a","b","c"]. [Link](delim,
parts) — joins: [Link]("-","2026","06","11") → "2026-06-11". [Link](fmt, args) — like
printf but returns String. concat(str) — appends (same as + operator). Comparison Methods:
equals(str) — case-sensitive content comparison. equalsIgnoreCase(str) — case-insensitive.
compareTo(str) — lexicographic order (0, negative, positive). Used for sorting. Conversion:
[Link](x) — any primitive or object to String. [Link]("123") — String to int.
13. Describe string comparison methods.
String comparison is one of the most common Java operations and a frequent source of bugs
when done incorrectly. The Golden Rule — Never Use == for String Content: The ==
operator compares object references (memory addresses), NOT the character content. Two
String objects can contain identical text but be different objects in heap memory, making ==
return false even when the content is the same. String s1 = new String("Java"); String s2 =
new String("Java"); s1 == s2 → FALSE (different heap objects, same content). String a =
"Java"; String b = "Java"; a == b → TRUE (both reference same pool object), but this is an
implementation detail you should never rely on. Always use equals() to compare String
content. equals(String other) — Exact Content Match: Case-sensitive comparison. Returns
true only if both strings have identical length and character sequence. "Java".equals("Java") →
true. "java".equals("Java") → false. "Java".equals(null) → false (no NullPointerException).
equalsIgnoreCase(String other) — Case-Insensitive Match:
"JAVA".equalsIgnoreCase("java") → true. "Java".equalsIgnoreCase("jAvA") → true. Use for:
user input validation where case shouldn't matter (country names, commands).
compareTo(String other) — Lexicographic Ordering: Returns 0 if equal. Returns negative if
this string comes before other alphabetically. Returns positive if this string comes after other.
The magnitude indicates how far apart the first differing characters are.
"apple".compareTo("banana") → negative (a < b). "java".compareTo("java") → 0. Used with
[Link]() and TreeMap for String ordering. compareToIgnoreCase(String other): Same
as compareTo() but ignores case differences. "Apple".compareToIgnoreCase("apple") → 0.
startsWith(String prefix) / endsWith(String suffix): "Hello World".startsWith("Hello") → true.
"[Link]".endsWith(".java") → true. startsWith(prefix, offset) checks from a specific position.
contains(CharSequence s): "Hello Java World".contains("Java") → true.
"test@[Link]".contains("@") → true. matches(String regex): Tests if the ENTIRE string
matches a regular expression. "12345".matches("[0-9]+") → true.
"hello@[Link]".matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+") → depends on pattern.
14. Explain StringBuffer operations.
StringBuffer is a mutable, thread-safe character sequence class in [Link]. Unlike String, its
internal char array can be modified directly, making it efficient for building strings through many
modifications. Creating a StringBuffer: StringBuffer sb = new StringBuffer(); — empty buffer,
initial capacity 16. StringBuffer sb = new StringBuffer("Hello"); — initialized with content.
StringBuffer sb = new StringBuffer(100); — empty buffer with capacity 100 (preallocates to
avoid frequent resizing). [Link]() — returns total allocated capacity. [Link]() — returns
current content length (≤ capacity). append() — Adding Content at End: The most used
method. Accepts any primitive or Object: [Link]("World"), [Link](42),
[Link](3.14), [Link](true), [Link]('!'). Returns the same StringBuffer — supports
method chaining: [Link]("a").append("b").append("c") → "abc" efficiently. insert() —
Inserting at a Position: [Link](index, value) — inserts at the specified position, shifting
subsequent characters right. StringBuffer sb = new StringBuffer("HelloWorld"); [Link](5, " ");
→ "Hello World". delete() / deleteCharAt(): [Link](start, end) — removes characters from
start (inclusive) to end (exclusive). [Link](index) — removes single character at that
index. StringBuffer sb = new StringBuffer("Hello!World"); [Link](5, 6); → "HelloWorld".
replace() — Replacing a Range: [Link](start, end, newStr) — replaces characters from
start to end-1 with newStr (newStr can be different length). reverse() — Reversing the
Sequence: [Link]() — reverses the character order in-place. StringBuffer sb = new
StringBuffer("Java"); [Link](); → "avaJ". Character-Level Access: [Link](i) — read
character at index. [Link](i, 'X') — write character at index. Converting Back to String:
[Link]() — creates a String with the current content. Required when passing to methods
that accept String. Thread Safety: All StringBuffer methods are synchronized. For
single-threaded code, use StringBuilder (identical API, not synchronized, faster by ~15-20%).
15. Discuss event listener interfaces.
Java's [Link] package defines a set of listener interfaces, each dedicated to a specific
category of events. Implementing these interfaces is how objects receive and process user
interactions. ActionListener: Interface with 1 method: void actionPerformed(ActionEvent e).
Used with: JButton, JMenuItem, JTextField (Enter), JComboBox. The simplest and most
common listener. The 1-method interface makes it ideal for lambda expressions:
[Link](e -> processClick([Link]())); MouseListener:
Interface with 5 methods: mouseClicked (press+release at same point), mousePressed (button
down), mouseReleased (button up), mouseEntered (cursor enters component), mouseExited
(cursor leaves). Registered: [Link](listener); Key data: getX(), getY(),
getButton(), getClickCount(). MouseAdapter — abstract class implementing all 5 with empty
bodies. Extend and override only needed methods. MouseMotionListener: Interface with 2
methods: mouseMoved (cursor moves, no button held), mouseDragged (cursor moves with
button held). Used for: drawing applications, drag-and-drop, custom hover effects. Register:
[Link](listener); KeyListener: Interface with 3 methods: keyPressed
(any key down), keyReleased (key up), keyTyped (Unicode char produced — excludes
non-printable keys like arrows, F-keys). Component must have keyboard focus:
[Link](); or [Link](true); KeyAdapter provides empty
implementations for convenient extension. ItemListener: Interface with 1 method: void
itemStateChanged(ItemEvent e). Used with: JCheckBox, JRadioButton, JComboBox.
[Link]() returns [Link] or DESELECTED. [Link]() returns the
affected item object. WindowListener: Interface with 7 methods. Critical: windowClosing —
called when user clicks X; use to save data or confirm exit. WindowAdapter — extend and
override only windowClosing() in most cases: addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { dispose(); } }); FocusListener: 2 methods:
focusGained, focusLost. Used for validation — validate a JTextField's content when focus
moves away from it. ChangeListener ([Link]): 1 method:
stateChanged(ChangeEvent e). Used with JSlider, JSpinner, JTabbedPane for continuous
value changes.
10-Mark Questions (Programs)
1. ActionListener event handling.
import [Link].*; import [Link].*;
public class ActionListenerDemo extends Frame implements ActionListener{
Button btnAdd,btnSub,btnMul,btnDiv,btnClr;
TextField tf1,tf2,tfRes; Label lblStatus;
ActionListenerDemo(){
setTitle("Calculator"); setLayout(new GridLayout(5,2,5,5));
add(new Label("Num 1:")); tf1=new TextField("0"); add(tf1);
add(new Label("Num 2:")); tf2=new TextField("0"); add(tf2);
add(new Label("Result:")); tfRes=new TextField(); [Link](false); add(tfRes);
btnAdd=new Button("Add"); btnSub=new Button("Sub"); btnMul=new Button("Mul");
btnDiv=new Button("Div"); btnClr=new Button("Clear");
[Link](this); [Link](this);
[Link](this); [Link](this);
[Link](this);
add(btnAdd); add(btnSub); add(btnMul); add(btnDiv);
lblStatus=new Label("Ready"); add(btnClr); add(lblStatus);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){dispose();}});
setSize(350,280); setVisible(true);
}
public void actionPerformed(ActionEvent e){
try{
double a=[Link]([Link]()), b=[Link]([Link]());
double r=0;
if([Link]()==btnAdd){r=a+b;[Link](a+"+"+b+"="+r);}
else if([Link]()==btnSub){r=a-b;[Link](a+"-"+b+"="+r);}
else if([Link]()==btnMul){r=a*b;[Link](a+"*"+b+"="+r);}
else if([Link]()==btnDiv){
if(b==0){[Link]("Cannot divide by zero!");return;}
r=a/b;[Link](a+"/"+b+"="+r);
}else{[Link]("0");[Link]("0");[Link]("");[Link]("Cleared");r
eturn;}
[Link]([Link]("%.4f",r));
}catch(NumberFormatException ex){[Link]("Enter valid numbers!");
[Link]("ERROR");}
}
public static void main(String[] a){new ActionListenerDemo();}
}
2. Mouse event handling.
import [Link].*; import [Link].*;
public class MouseEventDemo extends Frame implements MouseListener,MouseMotionListener{
Label lbl1,lbl2,lbl3; int mx,my,clicks=0;
MouseEventDemo(){
setTitle("Mouse Events"); setLayout(new BorderLayout());
Panel p=new Panel(new GridLayout(3,1));
lbl1=new Label("Move/click in window",[Link]);
lbl2=new Label("Coords: (0,0)",[Link]);
lbl3=new Label("Clicks: 0",[Link]);
[Link](lbl1); [Link](lbl2); [Link](lbl3);
Canvas c=new Canvas(){public void paint(Graphics g){
[Link]([Link]); [Link](mx-10,my,mx+10,my); [Link](mx,my-10,mx,my+10);
[Link](mx-4,my-4,8,8);
[Link]([Link]); [Link]("("+mx+","+my+")",mx+8,my-4);
}};
[Link]([Link]); [Link](this); [Link](this);
add(c,[Link]); add(p,[Link]);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){dispose();}});
setSize(500,380); setVisible(true);
}
public void mouseClicked(MouseEvent e){clicks++;mx=[Link]();my=[Link]();
[Link]("Clicked at ("+[Link]()+","+[Link]()+")"+([Link]()==2?"
DOUBLE":""));
[Link]("Clicks: "+clicks); ((Component)[Link]()).repaint();}
public void mousePressed(MouseEvent e){[Link]("Pressed");}
public void mouseReleased(MouseEvent e){[Link]("Released");}
public void mouseEntered(MouseEvent
e){[Link]("Entered");((Component)[Link]()).setBackground(new
Color(240,255,240));}
public void mouseExited(MouseEvent
e){[Link]("Exited");((Component)[Link]()).setBackground([Link]);}
public void mouseMoved(MouseEvent e){mx=[Link]();my=[Link]();
[Link]("Coords: ("+mx+","+my+")");((Component)[Link]()).repaint();}
public void mouseDragged(MouseEvent e){mx=[Link]();my=[Link]();
[Link]("Dragging: ("+mx+","+my+")");((Component)[Link]()).repaint();}
public static void main(String[] a){new MouseEventDemo();}
}
3. Keyboard event handling.
import [Link].*; import [Link].*;
public class KeyEventDemo extends Frame implements KeyListener{
TextArea taInput,taLog; Label lblKey,lblMod; int count=0;
KeyEventDemo(){
setTitle("Key Events"); setLayout(new BorderLayout(5,5));
Panel top=new Panel(new GridLayout(2,1));
lblKey=new Label("Press a key in text area",[Link]);
lblMod=new Label("Modifiers: None",[Link]);
[Link](lblKey); [Link](lblMod);
taInput=new TextArea("Type here...",5,40);
[Link](new Font("Courier",[Link],13));
[Link](this);
taLog=new TextArea("Key Log:\n",8,40);
[Link](false);
Panel bot=new Panel(new BorderLayout());
[Link](new Label("Log:"),[Link]);
[Link](taLog,[Link]);
[Link](new Label("Count: see below"),[Link]);
add(top,[Link]); add(taInput,[Link]);
add(bot,[Link]);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){dispose();}});
setSize(520,480); setVisible(true); [Link]();
}
public void keyPressed(KeyEvent e){
String mods="";
if([Link]())mods+="CTRL+"; if([Link]())mods+="ALT+";
if([Link]())mods+="SHIFT+";
[Link]("Modifiers: "+([Link]()?"None":mods));
[Link]("PRESSED: "+[Link]([Link]())+" code="+[Link]());
[Link]("PRESSED: "+[Link]([Link]())+"\n");
}
public void keyReleased(KeyEvent e){[Link]("RELEASED:
"+[Link]([Link]())+"\n");}
public void keyTyped(KeyEvent e){
char c=[Link]();
if(c!=KeyEvent.CHAR_UNDEFINED){count++;
String t=[Link](c)?"digit":[Link](c)?"letter":"symbol";
[Link]("TYPED: '"+c+"' char="+(int)c+" ("+t+") #"+count+"\n");
[Link]([Link]().length());
}
}
public static void main(String[] a){new KeyEventDemo();}
}
4. Frame and Panel GUI.
import [Link].*; import [Link].*;
public class FramePanelDemo extends Frame implements ActionListener{
TextField tfName,tfEmail,tfAge; TextArea taMsg;
Button btnSub,btnClr,btnExit; Label lblOut;
FramePanelDemo(){
setTitle("Student Form"); setLayout(new BorderLayout(8,8));
// NORTH - header
Panel header=new Panel();
[Link](new Color(0,80,160));
Label title=new Label(" STUDENT REGISTRATION FORM",[Link]);
[Link](new Font("Arial",[Link],16)); [Link]([Link]);
[Link](title);
// WEST - form fields
Panel form=new Panel(new GridLayout(6,2,6,6));
[Link](new Label("Full Name:")); tfName=new TextField(18); [Link](tfName);
[Link](new Label("Email:")); tfEmail=new TextField(18); [Link](tfEmail);
[Link](new Label("Age:")); tfAge=new TextField(5); [Link](tfAge);
[Link](new Label()); [Link](new Label());
[Link](new Label()); [Link](new Label());
[Link](new Label()); [Link](new Label());
// CENTER - message
Panel msgPanel=new Panel(new BorderLayout(4,4));
[Link](new Label("Message:"),[Link]);
taMsg=new TextArea(6,30); [Link](taMsg,[Link]);
// SOUTH - buttons
Panel south=new Panel(new BorderLayout());
Panel btns=new Panel(new FlowLayout([Link],12,5));
btnSub=new Button("Submit"); btnClr=new Button("Clear"); btnExit=new Button("Exit");
[Link](this); [Link](this);
[Link](this);
[Link](btnSub); [Link](btnClr); [Link](btnExit);
lblOut=new Label("Fill form and click Submit",[Link]);
[Link](btns,[Link]); [Link](lblOut,[Link]);
add(header,[Link]); add(form,[Link]);
add(msgPanel,[Link]); add(south,[Link]);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){dispose();}});
setSize(720,420); setVisible(true);
}
public void actionPerformed(ActionEvent e){
if([Link]()==btnSub) [Link]("Submitted: "+[Link]()+" |
"+[Link]());
else if([Link]()==btnClr){[Link]("");[Link]("");[Link]("");
[Link]("");[Link]("Cleared");}
else{dispose();}
}
public static void main(String[] a){new FramePanelDemo();}
}
5. FlowLayout and GridLayout demo.
import [Link].*; import [Link].*;
public class LayoutDemo extends Frame{
LayoutDemo(){
setTitle("Layout Demo"); setLayout(new BorderLayout(5,5));
// NORTH - FlowLayout
Panel flow=new Panel(new FlowLayout([Link],8,4));
[Link](new Color(200,220,255));
[Link](new Label("FlowLayout:"));
for(String s:new String[]{"File","Edit","View","Tools","Help"})
[Link](new Button(s));
// CENTER - GridLayout (calculator style)
Panel grid=new Panel(new GridLayout(4,4,2,2));
[Link](new Color(240,240,240));
String[] keys={"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
for(String k:keys){
Button b=new Button(k);
if([Link]("="))[Link](new Color(100,200,100));
else if("+-*/".contains(k))[Link](new Color(255,200,100));
[Link](b);
}
// SOUTH - status
Panel south=new Panel(new FlowLayout([Link],5,3));
[Link](new Label("GridLayout: 4x4 | FlowLayout: toolbar above"));
add(flow,[Link]);
add(grid,[Link]);
add(south,[Link]);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){dispose();}});
setSize(380,320); setVisible(true);
}
public static void main(String[] a){new LayoutDemo();}
}
6. Checkbox and radio button demo.
import [Link].*; import [Link].*;
public class CheckRadioDemo extends Frame implements ItemListener{
Checkbox cbJava,cbPy,cbCpp;
CheckboxGroup gGender; Checkbox rbMale,rbFemale,rbOther;
CheckboxGroup gExp; Checkbox rbFresh,rbJr,rbSr;
Label lblResult;
CheckRadioDemo(){
setTitle("Checkbox & RadioButton"); setLayout(new BorderLayout(8,8));
// Checkboxes - multiple select
Panel pLang=new Panel(new FlowLayout([Link]));
[Link](new Label("Skills: "));
cbJava=new Checkbox("Java"); cbPy=new Checkbox("Python"); cbCpp=new Checkbox("C++");
[Link](this); [Link](this); [Link](this);
[Link](cbJava); [Link](cbPy); [Link](cbCpp);
// Radio - mutually exclusive gender
Panel pGender=new Panel(new FlowLayout([Link]));
[Link](new Label("Gender: "));
gGender=new CheckboxGroup();
rbMale=new Checkbox("Male",gGender,true);
rbFemale=new Checkbox("Female",gGender,false);
rbOther=new Checkbox("Other",gGender,false);
[Link](this); [Link](this);
[Link](this);
[Link](rbMale); [Link](rbFemale); [Link](rbOther);
// Radio - experience
Panel pExp=new Panel(new FlowLayout([Link]));
[Link](new Label("Experience: "));
gExp=new CheckboxGroup();
rbFresh=new Checkbox("Fresher",gExp,true); rbJr=new Checkbox("Junior",gExp,false);
rbSr=new Checkbox("Senior",gExp,false);
[Link](this); [Link](this); [Link](this);
[Link](rbFresh); [Link](rbJr); [Link](rbSr);
Panel center=new Panel(new GridLayout(3,1));
[Link](pLang); [Link](pGender); [Link](pExp);
lblResult=new Label("Selected: ",[Link]);
add(center,[Link]); add(lblResult,[Link]);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){dispose();}});
setSize(480,220); setVisible(true); updateLabel();
}
void updateLabel(){
String langs=([Link]()?"Java ":"")+([Link]()?"Python
":"")+([Link]()?"C++ ":"");
String
g=[Link]()!=null?[Link]().getLabel():"-";
String x=[Link]()!=null?[Link]().getLabel():"-";
[Link]("Skills:["+[Link]()+"] Gender:"+g+" Exp:"+x);
}
public void itemStateChanged(ItemEvent e){updateLabel();}
public static void main(String[] a){new CheckRadioDemo();}
}
7. Applet lifecycle demo.
import [Link]; import [Link].*;
// To run: save as [Link]
// HTML: <applet code="[Link]" width="400" height="200"></applet>
public class AppletLifeCycle extends Applet{
String msg=""; int count=0;
public void init(){
msg="1. init() called";
[Link](msg);
setBackground(Color.LIGHT_GRAY);
}
public void start(){
count++;
msg+=" | 2. start() #"+count;
[Link]("start() called, count="+count);
repaint();
}
public void stop(){
[Link]("3. stop() called");
msg+=" | stop() #"+count;
}
public void destroy(){
[Link]("4. destroy() called");
}
public void paint(Graphics g){
[Link]([Link]);
[Link](new Font("Arial",[Link],16));
[Link]("Applet Lifecycle Demo",30,30);
[Link]([Link]);
[Link](new Font("Arial",[Link],13));
[Link](msg,10,60);
[Link]("start() called: "+count+" time(s)",10,90);
[Link]([Link]());
[Link](180,110,40,40);
[Link]([Link]);
[Link]("Applet running!",150,170);
}
}
8. String operations program.
public class StringOpsDemo{
public static void main(String[] args){
String s1="Hello World"; String s2="hello world"; String s3="Hello World";
[Link]("=== String Operations ===");
[Link]("Original: "+s1);
[Link]("length() : "+[Link]());
[Link]("charAt(4) : "+[Link](4));
[Link]("indexOf W : "+[Link]("World"));
[Link]("substr(6) : "+[Link](6));
[Link]("substr(0,5): "+[Link](0,5));
[Link]("upper : "+[Link]());
[Link]("lower : "+[Link]());
[Link]("replace : "+[Link]("World","Java"));
[Link]("contains : "+[Link]("World"));
[Link]("startsWith: "+[Link]("Hello"));
[Link]("endsWith : "+[Link]("World"));
[Link]("trim : "+ " spaces ".trim());
[Link]("\n=== Comparison ===");
[Link]("equals : "+[Link](s3));
[Link]("equalsIgn : "+[Link](s2));
[Link]("compareTo : "+[Link](s2));
[Link]("== refs : "+(s1==s3));
[Link]("\n=== Split ===");
String csv="Java,Python,C++,JavaScript";
String[] parts=[Link](",");
for(int i=0;i<[Link];i++) [Link]("parts["+i+"]="+parts[i]);
[Link]("\n=== StringBuffer ===");
StringBuffer sb=new StringBuffer("Hello");
[Link](" World").insert(5,",").delete(5,6).replace(6,11,"Java").reverse();
[Link]("After ops: "+sb);
[Link]("toString: "+[Link]());
}
}
9. String comparison methods.
public class StringComparison{
public static void main(String[] args){
String s1="Java"; String s2="JAVA"; String s3="Python"; String s4=new String("Java");
[Link]("=== equals ===");
[Link]("[Link](s4): "+[Link](s4)); // true (same content)
[Link]("s1==s4 : "+(s1==s4)); // false (diff objects)
[Link]("s1==\"Java\" : "+(s1=="Java")); // true (pool)
[Link]("\n=== equalsIgnoreCase ===");
[Link]("Java vs JAVA : "+[Link](s2)); // true
[Link]("Java vs Python: "+[Link](s3)); // false
[Link]("\n=== compareTo ===");
[Link]("Java vs JAVA : "+[Link](s2)); // positive (lowercase >
uppercase)
[Link]("Java vs Python: "+[Link](s3)); // negative (J < P)
[Link]("Java vs Java : "+[Link](s4)); // 0 (equal)
[Link]("\n=== startsWith / endsWith ===");
[Link]("startsWith J : "+[Link]("J"));
[Link]("endsWith a : "+[Link]("a"));
[Link]("\n=== contains / matches ===");
String email="test@[Link]";
[Link]("contains @ : "+[Link]("@"));
[Link]("is email? :
"+[Link]("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"));
[Link]("is digits? : "+"12345".matches("[0-9]+"));
[Link]("\n=== Sorting strings ===");
String[] words={"Banana","apple","Cherry","date"};
[Link](words,String.CASE_INSENSITIVE_ORDER);
for(String w:words) [Link](w+" ");
[Link]();
}
}
10. StringBuffer operations program.
public class StringBufferOps{
public static void main(String[] args){
StringBuffer sb=new StringBuffer();
[Link]("Empty sb capacity: "+[Link]()); // 16 default
sb=new StringBuffer("Hello");
[Link]("Initial: ["+sb+"] len="+[Link]()+" cap="+[Link]());
[Link](" Java"); [Link]("append: "+sb);
[Link](2026); [Link]("append int: "+sb);
[Link](10," "); [Link]("insert(10): "+sb);
[Link](10,11); [Link]("delete(10,11): "+sb);
[Link](6,10,"World"); [Link]("replace: "+sb);
[Link](); [Link]("reverse: "+sb);
[Link](); [Link]("restore: "+sb);
[Link]("charAt(0): "+[Link](0));
[Link](0,'h'); [Link]("setCharAt: "+sb);
[Link]("indexOf World: "+[Link]("World"));
[Link]("substring(6): "+[Link](6));
String result=[Link]();
[Link]("toString type: "+[Link]().getSimpleName());
// Performance
long t1=[Link]();
StringBuffer sb2=new StringBuffer();
for(int i=0;i<50000;i++) [Link](i);
[Link]("\nAppend 50000 ints: "+([Link]()-t1)+"ms");
// StringBuilder comparison
long t2=[Link]();
StringBuilder sb3=new StringBuilder();
for(int i=0;i<50000;i++) [Link](i);
[Link]("StringBuilder 50000: "+([Link]()-t2)+"ms (no sync
= faster)");
}
}
UNIT – IV
Exception Handling, Multithreading, Collections, Generics, JavaBeans
2-Mark Questions
1. What is an exception in Java?
An exception is an abnormal event that disrupts normal program flow at runtime. When an
exception occurs, an exception object is created containing the error type and stack trace.
Java uses try-catch-finally blocks to handle exceptions gracefully. Examples:
ArithmeticException (divide by zero), NullPointerException,
ArrayIndexOutOfBoundsException.
2. Define checked exception.
Checked exceptions are verified by the compiler at compile time. The programmer MUST
handle them using try-catch or declare with 'throws' — otherwise the code won't compile.
Examples: IOException, SQLException, ClassNotFoundException, FileNotFoundException.
They extend Exception but not RuntimeException.
3. Define unchecked exception.
Unchecked exceptions are NOT checked at compile time — they occur at runtime. The
compiler does NOT force handling. They extend RuntimeException. Examples:
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
ClassCastException, NumberFormatException.
4. What is try block?
The try block encloses code that might throw an exception. If an exception occurs inside try,
execution immediately jumps to the matching catch block — remaining try statements are
skipped. Syntax: try { risky code; } catch(ExceptionType e) { handler; }
5. What is catch block?
The catch block catches and handles a specific exception type thrown from the try block.
Multiple catch blocks can follow one try to handle different exception types. The parameter 'e'
holds the exception object. Methods: [Link]() (error message), [Link]() (class +
message), [Link]() (full stack trace).
6. What is finally block?
The finally block ALWAYS executes regardless of whether an exception occurred or was
caught — including when a return statement is in try or catch. Used to release resources
(close files, database connections). Syntax: try { } catch(E e) { } finally { cleanup code; } Only
skipped if [Link]() is called or JVM crashes.
7. What is multithreading?
Multithreading is the ability to execute two or more threads concurrently within a single
program. Each thread is an independent path of execution sharing the process's memory.
Improves performance on multi-core CPUs. Java has built-in support via Thread class and
Runnable interface.
8. Define thread life cycle.
A thread passes through 5 states: New — created but not started. Runnable — start() called,
ready to run. Running — CPU executing run(). Blocked/Waiting — waiting for I/O, lock, or
sleep(). Terminated/Dead — run() completed or stop() called.
9. What is thread synchronization?
Synchronization prevents multiple threads from simultaneously accessing shared resources,
avoiding data corruption (race conditions). The 'synchronized' keyword on a method or block
ensures only one thread at a time can execute that code — others wait for the lock to be
released.
10. What is Runnable interface?
Runnable is a functional interface in [Link] with one method: run(). A class implements
Runnable and passes an instance to a Thread constructor. Preferred over extending Thread
because the class can still extend other classes. Lambda compatible: Thread t = new
Thread(() -> { task code });
11. What is Thread class?
Thread class in [Link] provides all thread management functionality. Key methods: start()
(start execution), run() (task body), sleep(ms) (pause), join() (wait for thread to finish),
setPriority(n) (1=MIN, 10=MAX, 5=NORM), getName(), isAlive(). A class extends Thread and
overrides run().
12. What is collection framework?
Java Collections Framework is a unified architecture for storing and manipulating groups of
objects. Provides: Interfaces (List, Set, Map, Queue, Deque), Implementations (ArrayList,
HashSet, HashMap, etc.), Algorithms ([Link], shuffle, min, max). Replaces arrays for
most flexible data storage needs.
13. What is JavaBeans?
A JavaBean is a reusable software component — a Java class following conventions: (1)
Public no-arg constructor. (2) Private fields. (3) Public getters (getXxx()) and setters (setXxx()).
(4) Implements [Link]. Used in Spring, JSP (jsp:useBean), IDE tools, and
frameworks for component-based development.
14. What is generics in Java?
Generics allow classes, interfaces, and methods to operate on parameterized types specified
at compile time. Syntax: ArrayList<String>. Benefits: Type safety (compile-time error instead of
ClassCastException at runtime), Eliminates explicit casting, Code reuse for any type. Type
parameter: <T> convention.
15. What is security manager in Java?
SecurityManager is a class allowing applications to implement a custom security policy. It
checks access to system resources (files, network, threads, class loading) before allowing
operations. Installed via [Link](). Deprecated in Java 17 due to
architectural issues.
16. What is thread priority?
Thread priority is a hint to the thread scheduler about which threads should get more CPU
time. Range: Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), default
Thread.NORM_PRIORITY (5). Set with [Link](7). Higher priority threads are scheduled
more often but behavior is platform-dependent and NOT guaranteed.
17. What is deadlock?
Deadlock is a situation where two or more threads permanently block each other, each waiting
for a lock held by another. Thread A holds Lock 1, waits for Lock 2; Thread B holds Lock 2,
waits for Lock 1 — both wait forever. Prevention: always acquire locks in consistent order; use
tryLock() with timeout.
18. What is exception handling?
Exception handling is the mechanism to detect, intercept, and recover from runtime errors
without program crash. Java keywords: try (risky code), catch (handle specific exception),
finally (always runs), throw (manually raise exception), throws (declare exceptions a method
may throw).
19. What is ArrayList?
ArrayList ([Link]) is a resizable array implementation of the List interface. Allows duplicates
and null values. Maintains insertion order. Key methods: add(e), add(i,e), get(i), set(i,e),
remove(i), size(), contains(e), indexOf(e), clear(), sort(comparator). Not synchronized — use
[Link]() for thread safety.
20. What is HashMap?
HashMap ([Link]) implements Map using a hash table. Stores key-value pairs — keys are
unique, values can repeat. Allows one null key and multiple null values. No guaranteed order.
Key methods: put(k,v), get(k), remove(k), containsKey(k), containsValue(v), keySet(), values(),
entrySet(), size(). O(1) average for put/get.
5-Mark Questions
1. Explain exception handling mechanism in Java.
Exception handling is Java's structured mechanism to deal with runtime errors gracefully,
keeping programs stable rather than crashing on unexpected conditions. The Exception
Hierarchy: All exceptions inherit from [Link]. Throwable has two direct
subclasses: Error (serious JVM-level problems — OutOfMemoryError, StackOverflowError —
not typically handled by programs) and Exception. Exception splits into: Checked Exceptions
(extend Exception directly — must be handled or declared) and Unchecked Exceptions
(extend RuntimeException — handling optional). The Five Exception Keywords: try:
Encloses code that might throw an exception. If an exception occurs, execution jumps
immediately to the matching catch block. Code after the throw point in the try block is skipped.
catch: Catches a specific exception type and provides handling code. Multiple catch blocks
can follow one try — most specific exception types first, general ones last. Java 7+ multi-catch:
catch(IOException | SQLException e) handles multiple types in one block. finally: Executes
unconditionally after try-catch, whether or not an exception was thrown or caught. Used for
resource cleanup — ensures files are closed, connections released. Only skipped on
[Link]() or JVM crash. throw: Manually throws an exception object: throw new
IllegalArgumentException("age must be positive"); Can throw any Throwable. Stops current
execution flow. throws: Declares in a method signature that the method may throw checked
exceptions, so callers must handle them: void readFile(String path) throws IOException,
FileNotFoundException. try-with-resources (Java 7+): try (BufferedReader br = new
BufferedReader(new FileReader("[Link]"))) { [Link](); } Resources implementing
AutoCloseable are automatically closed on exit. Cleaner than explicit finally blocks. Custom
Exceptions: Create domain-specific exceptions: class InsufficientFundsException extends
Exception { InsufficientFundsException(double amount) { super("Insufficient by Rs." +
amount); } }
2. Differentiate checked and unchecked exceptions.
Java's exception system divides exceptions into two fundamental categories based on when
they are detected and whether handling is mandatory. Checked Exceptions: Checked
exceptions are detected by the Java compiler at compile time. If any code calls a method that
can throw a checked exception, the compiler demands that the calling code either: (a)
Surrounds the call with a try-catch block that catches the exception, OR (b) Declares the
exception in its own 'throws' clause, propagating the responsibility to callers. If neither is done,
the code simply will not compile — the compiler flags it as an error. The rationale: checked
exceptions represent external conditions that are unpredictable and recoverable — network
errors, file not found, database connectivity issues. These are situations where the
programmer is expected to handle the failure gracefully (retry, fall back, inform user).
Examples: IOException (any I/O failure), FileNotFoundException (file missing), SQLException
(database error), ClassNotFoundException (class loading failure), InterruptedException
(thread interrupted during sleep/wait), ParseException (date/number format error). They
extend [Link] but NOT RuntimeException. Unchecked Exceptions: Unchecked
exceptions are NOT detected at compile time — they only manifest at runtime when the
problematic code actually executes. The compiler does not require you to handle or declare
them. If unhandled, they propagate up the call stack until they reach main(), at which point the
JVM prints the stack trace and the program terminates. The rationale: unchecked exceptions
typically represent programming errors — logical bugs in the code that should be fixed rather
than caught. Trying to dereference null, accessing an array index that doesn't exist, dividing by
zero — these indicate a bug in the program logic, not an external failure. Examples:
NullPointerException (null reference), ArrayIndexOutOfBoundsException (bad index),
ArithmeticException (divide by zero), ClassCastException (invalid downcast),
NumberFormatException (invalid numeric string), IllegalArgumentException,
StackOverflowError. They extend RuntimeException (which extends Exception). Rule of
Thumb: Use checked exceptions for recoverable external errors. Use unchecked exceptions
for programming errors that indicate bugs.
3. Explain try-catch-finally blocks with example.
The try-catch-finally construct is Java's primary tool for structured exception handling. It
separates normal code from error-handling code, making programs more robust and readable.
try Block — Guarded Code: The try block contains code that might throw exceptions. Normal
program logic goes here. As soon as any statement inside the try block throws an exception,
execution immediately jumps to the appropriate catch block — no remaining try statements
execute. If NO exception is thrown, all catch blocks are skipped, and execution continues after
the entire try-catch-finally structure. catch Block — Exception Handler: Each catch block
handles a specific exception type (or multiple types with |). The catch parameter provides
access to the exception object, which carries: getMessage() — a human-readable description,
toString() — class name + message, printStackTrace() — the full call stack at the time of
exception, getClass().getSimpleName() — just the exception class name. Multiple catch blocks
are evaluated in order — put more specific exceptions (like FileNotFoundException) before
general ones (like IOException), or the compiler will warn that the specific catch is
unreachable. finally Block — Always Executes: The finally block runs after the try block
completes (normally or via exception) and after any matched catch block runs. It provides a
guaranteed cleanup point. Even if a catch block throws another exception, the finally block
runs first. Resources declared in try-with-resources are closed automatically as a modern
alternative. Execution Flow: No exception: try(all statements) → skip catch → finally →
continue. Exception caught: try(statements until throw) → matching catch → finally →
continue. Exception not caught: try(statements until throw) → finally → exception propagates
up. Nested try-catch: try blocks can be nested. An inner exception not caught inside
propagates to the outer try-catch. This allows fine-grained handling at different levels of code.
4. Describe thread life cycle.
A Java thread goes through a well-defined sequence of states during its lifetime, managed by
the JVM thread scheduler. State 1 — New: A Thread object has been created but start() has
not yet been called. The thread exists in memory but has no execution resources allocated to
it. It is just an object at this point. Example: Thread t = new Thread(myRunnable); — t is in
New state. State 2 — Runnable: start() has been called. The thread is ready to run and is in
the thread pool, waiting for the CPU to be assigned by the thread scheduler. 'Runnable'
doesn't mean it IS running — it means it CAN run. On a single-core machine, only one thread
runs at any instant; the others eligible to run are in Runnable state. On multi-core machines,
multiple threads can actually run simultaneously. State 3 — Running: The thread scheduler
has selected this thread and the CPU is executing its run() method. This state is transient —
the scheduler can move the thread back to Runnable at any time (time slice expired,
higher-priority thread becomes runnable). State 4 — Blocked / Waiting / Timed Waiting: The
thread is temporarily suspended and cannot be scheduled until a specific condition is met.
Blocked: Trying to acquire a synchronized lock held by another thread. Waiting: Called wait()
— waiting for another thread to call notify() or notifyAll(). Timed Waiting: Called sleep(ms),
wait(ms), or join(ms) — automatically returns after the timeout expires. State 5 — Terminated
(Dead): The run() method has completed normally, or an unhandled exception caused it to
exit, or stop() was called (deprecated). A terminated thread cannot be restarted — calling
start() on a terminated thread throws IllegalThreadStateException.
5. Explain multithreading vs multitasking.
Both multitasking and multithreading provide concurrency — the appearance or reality of
multiple tasks executing simultaneously — but they operate at different levels. Multitasking
(Process-Level Concurrency): Multitasking is the ability of an operating system to run
multiple processes concurrently. Each process is an independent program with its own
memory space, file handles, and resources. The OS context-switches between processes to
give the appearance of simultaneous execution. Context switching between processes is
expensive because the OS must save and restore the entire process state (registers, memory
mappings, file descriptors, program counter). Memory: Processes do NOT share memory by
default. Inter-process communication (IPC) requires special mechanisms (pipes, sockets,
shared memory) which are complex and slow. Failure isolation: One process crashing does
not directly affect others. Example: Running a browser, text editor, and music player
simultaneously. Multithreading (Thread-Level Concurrency within a Process):
Multithreading is the ability of a single process to have multiple threads of execution running
within it. All threads in a process share the same heap memory, static variables, and open file
handles. Each thread only has its own stack (local variables) and program counter. Context
switching between threads of the same process is much cheaper than between processes
because no memory remapping is needed. Communication: Threads communicate easily by
sharing objects in the shared heap — but this requires synchronization to prevent race
conditions and data corruption. Failure: An unhandled exception in one thread can crash the
entire process. Use cases: A web server handling many client connections concurrently, a GUI
application keeping the UI responsive while doing background processing, parallel
computation on multi-core hardware. Java's Multithreading Advantage: Java has first-class,
built-in multithreading support via Thread class, Runnable interface, synchronized keyword,
wait/notify, volatile, and the [Link] package with thread pools, locks, atomic
variables, and concurrent collections.
6. Explain thread creation using Thread class.
The first way to create a thread in Java is to extend the Thread class and override its run()
method. The run() method contains the code that will execute in the new thread. Steps: Step 1
— Create a subclass of Thread: class MyTask extends Thread { ... } Step 2 — Override run()
with the task logic: public void run() { for(int i=1; i<=5; i++) { [Link](getName() + ": "
+ i); try { [Link](500); } catch(InterruptedException e) { } } } Step 3 — Create an
instance: MyTask t = new MyTask("Worker-1"); [Link]("Worker-1"); Step 4 — Start the
thread: [Link](); — This creates a new OS-level thread and invokes run() in that thread.
Critical Distinction: [Link]() — this is just a regular method call, executes in the CURRENT
thread (NOT a new thread). [Link]() — this creates a NEW thread of execution and calls run()
in that thread. Always call start(), not run(), to achieve true concurrency. Important Thread
Methods: start() — starts the thread (can only be called once per Thread object).
sleep(milliseconds) — pauses current thread for specified time (throws InterruptedException).
join() — calling thread waits for this thread to finish. join(ms) — waits at most ms milliseconds.
setPriority(n) — sets scheduling priority (1-10). setName(name) / getName() — set/get thread
identifier name. isAlive() — returns true if thread is started but not yet terminated.
[Link]() — static method returning the currently executing thread. Limitation
of Extending Thread: Java supports only single inheritance. If a class extends Thread, it
cannot extend any other class. For classes that already have a parent class, the Runnable
interface approach must be used instead.
7. Explain thread creation using Runnable interface.
The second and preferred way to create a thread in Java is to implement the Runnable
interface. Runnable is in [Link] and defines one method: void run(). The Runnable object
encapsulates the task; a Thread object is needed to actually execute it. Steps: Step 1 —
Implement Runnable: class PrintTask implements Runnable { String msg; int reps;
PrintTask(String m, int r) { msg=m; reps=r; } public void run() { for(int i=0; i<reps; i++) {
[Link]([Link]().getName() + ": " + msg); try { [Link](300); }
catch(InterruptedException e) { [Link]().interrupt(); } } } } Step 2 — Create a
Runnable instance: PrintTask task = new PrintTask("Hello", 5); Step 3 — Wrap it in a Thread:
Thread t = new Thread(task, "ThreadName"); Step 4 — Start it: [Link](); Why Runnable is
Preferred: No inheritance constraint: The class implementing Runnable can still extend any
other class. This is important when the task-performing class already has a parent (e.g., class
NetworkHandler extends BaseHandler implements Runnable). Better design: Separates the
task (what to run) from the thread mechanism (how to run). The same Runnable can be
submitted to different executors or thread pools. Thread pool compatibility: Thread pools
(ExecutorService) accept Runnable and Callable — not Thread subclasses. Lambda
Expressions (Java 8+): Since Runnable is a functional interface (one abstract method),
lambdas work perfectly: Thread t = new Thread(() -> { for(int i=0; i<5; i++)
[Link]("Lambda: "+i); }, "LambdaThread"); [Link](); Sharing a Runnable: One
Runnable instance can be shared by multiple Thread objects. If the Runnable has shared
state, synchronization is required.
8. Discuss thread synchronization.
When multiple threads access and modify shared data concurrently without coordination, the
results can be unpredictable and incorrect — this is called a race condition. Thread
synchronization prevents this. The Race Condition Problem: Consider a bank account with
balance = 1000. Thread A reads balance (1000) and plans to withdraw 800. Before A updates
the balance, Thread B also reads balance (still 1000) and withdraws 700. Both withdraw
successfully, leaving the balance negative — an impossible state. Without synchronization, the
two reads and two writes interleave unpredictably. synchronized Keyword: The synchronized
keyword creates a mutual exclusion lock (monitor lock). Only one thread can hold the monitor
of a given object at a time. Other threads that try to enter a synchronized block/method on the
same object are blocked until the lock is released. Synchronized Method: synchronized void
withdraw(int amount) { if(balance >= amount) { balance -= amount; } } When Thread A is inside
this method, Thread B cannot enter ANY synchronized method of the same object — it waits
until A exits. Synchronized Block: More fine-grained than synchronized method. Locks only a
specific section of code: void transfer(Account target, int amount) { synchronized(this) {
balance -= amount; } synchronized(target) { [Link] += amount; } } wait(), notify(),
notifyAll(): Used inside synchronized blocks for thread coordination: wait() — releases the
lock and suspends the thread until another thread calls notify(). notify() — wakes up one
thread waiting on this object's monitor. notifyAll() — wakes up all waiting threads. Classic use:
producer-consumer pattern — producer notifies consumer when data is ready; consumer waits
when buffer is empty. Volatile Keyword: Ensures that reads/writes to a variable go directly to
main memory (not cached in thread-local memory). Guarantees visibility of the latest value
across threads, but does NOT provide atomicity for compound operations like i++.
9. Explain Java collection framework.
The Java Collections Framework (JCF) is a unified architecture in [Link] for storing,
retrieving, and manipulating groups of objects. It provides interfaces, concrete
implementations, and algorithms. Core Interfaces: Collection<E>: Root interface for
single-element collections. Provides add(), remove(), contains(), size(), isEmpty(), iterator(),
toArray(). Extended by List, Set, Queue. List<E>: Ordered collection. Allows duplicates.
Indexed access via get(i). ArrayList — dynamic array, fast random access O(1), slow
insertion/deletion in middle O(n). Best for frequent reads. LinkedList — doubly linked list, fast
insertion/deletion O(1), slow random access O(n). Also implements Deque. Best for frequent
insertions/deletions. Vector — like ArrayList but synchronized (thread-safe, slower). Set<E>:
Collection with no duplicates. add() returns false if element already exists. HashSet — fastest,
O(1) add/contains, no ordering. Uses hashCode() and equals(). TreeSet — sorted order
(natural or Comparator), O(log n) operations. Implements SortedSet. LinkedHashSet —
maintains insertion order, O(1) operations. Map<K,V>: Key-value pairs. Keys unique, values
can repeat. NOT a Collection subtype. HashMap — fastest, O(1) put/get, no ordering. Allows
one null key. TreeMap — keys in sorted order, O(log n). Implements SortedMap.
LinkedHashMap — maintains insertion order. Queue<E>: FIFO ordering. offer(e) adds, poll()
removes head, peek() reads head without removing. PriorityQueue — orders by priority
(natural order or Comparator). Deque<E>: Double-ended queue. ArrayDeque — efficient
stack and queue. addFirst/addLast, removeFirst/removeLast. Collections Utility Class:
[Link](list) — sorts List. [Link](list, comparator) — custom order.
[Link](list) — random order. [Link](list). [Link](coll),
[Link](coll). [Link](coll, obj).
10. Describe ArrayList and HashMap.
ArrayList and HashMap are the two most frequently used collection implementations in Java.
ArrayList<E> ([Link]): ArrayList is a resizable array implementation of the List
interface. It maintains a dynamic array internally that grows automatically (typically doubles
when full). Elements are stored in insertion order, duplicates are allowed, and null values are
permitted. Time Complexity: get(i) and set(i,e) — O(1) (direct array access). add(e) to end —
O(1) amortized. add(i,e) in middle or remove(i) — O(n) (elements must shift). contains(e) —
O(n) (linear scan). Key Methods: add(e) — appends. add(i, e) — inserts at index. get(i) —
retrieves. set(i, e) — replaces. remove(i) — removes by index. remove(obj) — removes first
occurrence. size() — count. contains(e) — membership test. indexOf(e) — first position. clear()
— remove all. [Link](list) — in-place sort. [Link](Comparator) — custom sort.
subList(from, to) — view of a range. toArray() — convert to Object[]. Not synchronized — use
[Link](new ArrayList<>()) or CopyOnWriteArrayList for thread safety.
HashMap<K,V> ([Link]): HashMap is a hash table implementation of the Map
interface. It stores entries as key-value pairs. Each key maps to exactly one value. Keys must
be unique (determined by hashCode() and equals()). Values can be duplicated. One null key is
allowed; multiple null values are allowed. No ordering guarantee. Time Complexity: put(k,v),
get(k), remove(k), containsKey(k) — O(1) average. O(n) worst case (all keys hash to same
bucket — rare with good hashCode). Key Methods: put(k,v) — add/update entry. get(k) —
retrieve value (null if not present). getOrDefault(k, default) — safer get. remove(k) — delete
entry. containsKey(k), containsValue(v). size(), isEmpty(), clear(). keySet() — Set of all keys.
values() — Collection of all values. entrySet() — Set<[Link]<K,V>> for iterating pairs.
putIfAbsent(k,v) — only adds if key absent. merge(k, v, BiFunction) — combine old and new
value. Iteration: for([Link]<String,Integer> entry : [Link]()) { sysout([Link]()
+ " = " + [Link]()); } Not synchronized — use ConcurrentHashMap for thread-safe
concurrent access.
11. Explain generics with example.
Generics (introduced in Java 5) allow classes, interfaces, and methods to be parameterized by
type. The actual type is specified at instantiation/call time, enabling a single implementation to
work safely with many types. The Problem Generics Solve: Before generics, collections
stored Object references: ArrayList list = new ArrayList(); [Link]("Hello"); [Link](42); String s
= (String) [Link](1); — ClassCastException at runtime! The error only appears at runtime,
which is dangerous. With generics: ArrayList<String> list = new ArrayList<>(); [Link]("Hello");
[Link](42); — COMPILE ERROR immediately. String s = [Link](0); — no cast needed. Errors
caught early, code cleaner. Generic Class: Parameterized type T acts as a placeholder
replaced by the actual type at instantiation. class Pair<T, U> { T first; U second; Pair(T f, U s) {
first=f; second=s; } } Usage: Pair<String, Integer> p = new Pair<>("Age", 25); — T=String,
U=Integer. Generic Method: A method with its own type parameter: public <T extends
Comparable<T>> T findMax(T[] arr) { T max = arr[0]; for(T x : arr) if([Link](max) > 0)
max = x; return max; } Finds max in any Comparable array — Integer[], String[], Double[]. No
casting needed. Bounded Type Parameters: <T extends Number> — T must be Number or
its subclass (Integer, Double, etc.). <T extends Comparable<T>> — T must implement
Comparable (for sorting/comparison). <T super Integer> — T must be Integer or a supertype
(lower bounded wildcard). Wildcards: List<?> — unknown type, read-only. List<? extends
Number> — any Number subtype (upper bounded, read-mostly). List<? super Integer> —
Integer or supertype (lower bounded, write-capable). Type Erasure: At runtime, all generic
type parameters are erased and replaced with Object (or the bound). Generic type information
exists only at compile time. This is why you cannot do new T() or create an array of a generic
type directly.
12. Explain JavaBeans concept.
JavaBeans is a specification for writing reusable, portable Java components. A JavaBean is a
Java class that follows a set of simple conventions, enabling tools, frameworks, and IDEs to
discover and use its properties programmatically. The Four JavaBeans Conventions: 1.
Public No-Argument Constructor: Every JavaBean must have a public constructor that
takes no parameters. This allows frameworks (Spring, JSP containers, IDEs) to instantiate the
bean without knowing the constructor arguments. If you define only parameterized
constructors, the no-arg constructor is NOT automatically provided — you must explicitly write
it. Example: public StudentBean() { } — required even if empty. 2. Private Fields
(Encapsulation): All state (data) is stored in private instance variables. This enforces
encapsulation — external code cannot directly access or modify the bean's data. All access
goes through the getter/setter API. Example: private String name; private int age; private
double gpa; 3. Public Getter Methods (Accessors): For each property, a public method that
returns its value. The naming convention is: getPropertyName() for regular properties.
isPropertyName() for boolean properties. These methods allow frameworks to READ bean
properties. Example: public String getName() { return name; } public boolean isActive() { return
active; } 4. Public Setter Methods (Mutators): For each writable property, a public method
that accepts a new value. The naming convention is: setPropertyName(type value). Setters
allow frameworks to WRITE bean properties. They can include validation logic. Example:
public void setName(String name) { if(name != null) [Link] = name; } public void setAge(int
age) { if(age >= 0 && age < 150) [Link] = age; } 5. Implements Serializable: JavaBeans
should implement [Link] to support object persistence (saving to disk, sending
over network). Provide a serialVersionUID for version control. Where JavaBeans Are Used:
JSP Expression Language: ${[Link]} automatically calls getName(). Spring
Framework: Auto-wires bean properties from configuration. IDE property editors: Inspect and
set bean properties at design time. JPA/Hibernate: Maps bean properties to database
columns.
13. Discuss importance of security manager.
The SecurityManager class in [Link] provides an access control mechanism that Java
applications can use to enforce security policies when running untrusted code. Core Purpose:
The SecurityManager acts as a gatekeeper between Java code and sensitive system
resources. Before performing potentially dangerous operations, the JVM checks with the
installed SecurityManager — if the SecurityManager denies the request, a SecurityException
is thrown and the operation is blocked. What SecurityManager Controls: File System:
Reading/writing specific files or directories. Class Loading: Defining new classes or accessing
specific class loaders. Network: Creating network connections to specific hosts/ports. Thread
Management: Creating threads, stopping threads, accessing thread groups. Reflection:
Accessing private members of classes. System Properties: Reading/writing system properties.
Process Execution: Running system commands. Shutdown: Calling [Link](). How It
Works: The SecurityManager is installed once per JVM: [Link](new
SecurityManager()); Key permission-checking methods (all called internally by JVM before
operations): checkRead(filename), checkWrite(filename), checkConnect(host, port),
checkCreateThread(), checkExec(cmd), checkExit(status), checkPermission(Permission p). If
a check method does nothing (returns normally), the operation proceeds. If it throws
SecurityException, the operation is blocked. Custom Security Policies: Extend
SecurityManager and override specific check methods to implement custom rules: class
AppSecurityManager extends SecurityManager { public void checkRead(String file) {
if([Link]("/etc/passwd")) throw new SecurityException("Access denied: " + file);
[Link](file); } } Current Status: SecurityManager is deprecated since Java 17 and
scheduled for removal in a future release. The rationale: it was mainly used for applets (now
dead) and has architectural issues making it hard to use correctly. Modern Java applications
use OS-level permissions, container security, and module-system encapsulation instead.
14. Compare Thread class and Runnable interface.
Java provides two approaches to define thread behavior. Each has distinct advantages that
make one better suited for different situations. Extending Thread Class: A class extends
Thread and overrides the run() method. The class itself IS a thread — it carries both the task
logic and all Thread's lifecycle management. class DownloadTask extends Thread { String url;
DownloadTask(String u) { url=u; setName("Downloader"); } public void run() { download(url); } }
Usage: new DownloadTask("[Link] Limitation — Single Inheritance: Java does not
allow a class to extend more than one class. If your class already extends another class (e.g.,
class NetworkHandler extends BaseHandler), it cannot also extend Thread. This is a serious
design constraint. Tight coupling: The task (download logic) is tightly coupled to the thread
mechanism. The same download logic cannot be easily reused with different concurrency
mechanisms (like thread pools). Implementing Runnable Interface: A class implements
Runnable and provides a run() method. The class is a task, not a thread. A separate Thread
object is needed to execute it. class DownloadTask implements Runnable { String url;
DownloadTask(String u) { url=u; } public void run() { download(url); } } Usage: new Thread(new
DownloadTask("[Link] "Downloader").start(); Advantages: No inheritance constraint — the
task class can extend any other class and still be runnable. Better separation of concerns —
task logic is decoupled from thread mechanism. The same Runnable instance can be
submitted to a thread pool, scheduled executor, or any other concurrency framework. Lambda
compatible (Java 8+): new Thread(() -> download(url)).start(); Thread pool compatibility:
[Link](new DownloadTask(url)) — Runnable works with thread pools. You
cannot directly submit a Thread subclass. Verdict: Runnable is preferred in virtually all
modern Java code. The Runnable interface gives maximum flexibility with minimum coupling.
15. Explain deadlock in threads.
Deadlock is one of the most serious concurrency bugs — a situation where two or more
threads are permanently blocked, each holding a resource that another thread needs, and
waiting for a resource held by another, creating a circular dependency with no resolution.
Classic Deadlock Scenario: Thread A acquires Lock 1 (for Account A). Thread B acquires
Lock 2 (for Account B). Thread A now needs Lock 2 (to update Account B) — waits. Thread B
now needs Lock 1 (to update Account A) — waits. Both threads wait forever. The program is
hung. Neither thread ever releases its lock because it never finishes. Four Necessary
Conditions (Coffman Conditions): All four must be present simultaneously for deadlock: 1.
Mutual Exclusion: Resources cannot be shared simultaneously — only one thread holds a
lock at a time. 2. Hold and Wait: A thread holds at least one resource and is waiting to acquire
additional resources held by others. 3. No Preemption: Locks cannot be forcibly taken from a
thread — a thread must release them voluntarily. 4. Circular Wait: A circular chain of threads
exists where each holds a resource needed by the next. Prevention Strategies: Fixed Lock
Ordering: Always acquire multiple locks in the same predetermined global order. If both
Thread A and Thread B always lock Account with lower ID first, circular wait is impossible.
tryLock() with Timeout: Use [Link](timeout, unit) instead of synchronized. If
lock not acquired within timeout, back off and retry: if() {
/* back off */ } Avoid Nested Locks: Design code to acquire only one lock at a time when
possible. Complete work with one lock before acquiring another. Lock Ordering Utilities:
Assign a consistent numeric order to all lock objects and always acquire in ascending order.
Deadlock Detection: Java's VisualVM and jstack tools can detect deadlocked threads at
runtime for diagnosis.
10-Mark Questions (Programs)
1. Division by zero exception handling.
public class DivisionByZero{
public static void main(String[] args){
int[] nums={10,20,30,40}; int[] divs={2,0,5,0};
[Link]("=== Division with Exception Handling ===");
for(int i=0;i<[Link];i++){
try{
int result=nums[i]/divs[i];
[Link](nums[i]+" / "+divs[i]+" = "+result);
}catch(ArithmeticException e){
[Link]("Error dividing "+nums[i]+" by "+divs[i]+": "+[Link]());
}finally{
[Link](" finally: iteration "+i+" done");
}
}
[Link]("\nProgram continues normally after exception handling.");
// Multiple exception types
String[] strs={"42","hello",null,"0"};
for(String s:strs){
try{
int n=[Link](s);
int result=100/n;
[Link]("100/"+n+" = "+result);
}catch(NumberFormatException e){[Link]("'"+s+"' is not a number");}
catch(ArithmeticException e){[Link]("Cannot divide by zero");}
catch(NullPointerException e){[Link]("Null string encountered");}
}
}
}
2. NullPointerException and finally block.
public class NullAndFinally{
static void process(String s){
[Link]("Processing: "+s);
try{
[Link](" Length: "+[Link]());
[Link](" Upper : "+[Link]());
[Link](" Success!");
}catch(NullPointerException e){
[Link](" NullPointerException caught: "+[Link]().getSimpleName());
}finally{
[Link](" finally: cleanup for process()");
}
}
static int divide(int a, int b){
try{
return a/b;
}catch(ArithmeticException e){
[Link](" ArithmeticException: "+[Link]());
return -1;
}finally{
[Link](" finally in divide() - always runs");
}
}
public static void main(String[] args){
[Link]("--- Test 1: valid string ---");
process("Hello Java");
[Link]("\n--- Test 2: null string ---");
process(null);
[Link]("\n--- Test 3: divide ---");
[Link]("10/2 = "+divide(10,2));
[Link]("10/0 = "+divide(10,0));
[Link]("\nMain continues after all exception handling.");
}
}
3. Negative array size exception.
public class NegativeArraySize{
public static void main(String[] args){
int[] sizes={5,-3,4,-1,3};
for(int size:sizes){
[Link]("\nTrying size="+size+":");
try{
int[] arr=new int[size];
for(int i=0;i<[Link];i++) arr[i]=i*10;
[Link](" Array: ");
for(int x:arr) [Link](x+" ");
[Link]();
}catch(NegativeArraySizeException e){
[Link](" NegativeArraySizeException: size "+size+" not allowed");
}catch(Exception e){
[Link](" Unexpected: "+e);
}finally{
[Link](" finally block for size="+size);
}
}
[Link]("\n--- Array Index Out of Bounds ---");
int[] arr={1,2,3};
for(int i=0;i<=[Link];i++){
try{ [Link]("arr["+i+"]="+arr[i]);}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Index "+i+" out of bounds (length="+[Link]+")");
}
}
}
}
4. Multithreading using Thread class.
class Counter extends Thread{
String tname; int limit;
Counter(String n,int l){tname=n;limit=l;setName(n);}
public void run(){
for(int i=1;i<=limit;i++){
[Link](tname+" -> count: "+i+" (Priority:"+getPriority()+")");
try{[Link](400);}catch(InterruptedException
e){[Link]().interrupt();}
}
[Link](tname+" FINISHED.");
}
}
public class MultiThreadDemo{
public static void main(String[] args) throws InterruptedException{
Counter t1=new Counter("Thread-A",5);
Counter t2=new Counter("Thread-B",5);
Counter t3=new Counter("Thread-C",3);
[Link](Thread.MAX_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]("Starting threads...");
long start=[Link]();
[Link](); [Link](); [Link]();
[Link](); [Link](); [Link]();
[Link]("All threads done in "+([Link]()-start)+"ms");
[Link]("Main thread: "+[Link]().getName());
}
}
5. Thread using Runnable interface.
class PrintTask implements Runnable{
String msg; int count;
PrintTask(String m,int c){msg=m;count=c;}
public void run(){
for(int i=1;i<=count;i++){
[Link]([Link]().getName()+": "+msg+" ["+i+"/"+count+"]");
try{[Link](300);}catch(InterruptedException
e){[Link]().interrupt();break;}
}
}
}
public class RunnableDemo{
public static void main(String[] args) throws InterruptedException{
// Method 1: Class implementing Runnable
Runnable r1=new PrintTask("Download",4);
Runnable r2=new PrintTask("Upload",4);
Thread t1=new Thread(r1,"Worker-1");
Thread t2=new Thread(r2,"Worker-2");
// Method 2: Lambda (Java 8+)
Thread t3=new Thread(()->{
for(int i=1;i<=3;i++){
[Link]("Lambda thread: step "+i);
try{[Link](250);}catch(InterruptedException e){break;}
}
},"Lambda-Thread");
[Link](); [Link](); [Link]();
[Link](); [Link](); [Link]();
[Link]("All Runnable threads completed.");
}
}
6. Thread synchronization.
class BankAccount{
private String name; private double balance;
BankAccount(String n,double b){name=n;balance=b;}
synchronized void withdraw(String who,double amt){
[Link](who+" attempting Rs."+amt+" from "+name+"(bal:"+balance+")");
if(balance>=amt){
try{[Link](50);}catch(InterruptedException e){}
balance-=amt;
[Link](" SUCCESS: "+who+" withdrew Rs."+amt+" | New balance: Rs."+balance);
}else{
[Link](" FAILED: "+who+": insufficient. Need "+amt+" have "+balance);
}
}
synchronized void deposit(String who,double amt){
balance+=amt;
[Link](who+" deposited Rs."+amt+" | Balance: Rs."+balance);
}
double getBalance(){return balance;}
}
public class SyncDemo{
public static void main(String[] args) throws InterruptedException{
BankAccount acc=new BankAccount("Shared Account",1000);
Thread t1=new Thread(()->[Link]("Alice",700));
Thread t2=new Thread(()->[Link]("Bob",700));
Thread t3=new Thread(()->[Link]("Charlie",500));
[Link](); [Link](); [Link]();
[Link](); [Link](); [Link]();
[Link]("Final balance: Rs."+[Link]());
}
}
7. ArrayList demonstration.
import [Link].*;
public class ArrayListFull{
public static void main(String[] args){
ArrayList<String> list=new ArrayList<>();
[Link]("Mango"); [Link]("Apple"); [Link]("Banana");
[Link]("Orange"); [Link]("Apple"); // duplicate allowed
[Link]("List: "+list+" Size: "+[Link]());
[Link]("get(1): "+[Link](1));
[Link]("contains Apple: "+[Link]("Apple"));
[Link]("indexOf Apple: "+[Link]("Apple"));
[Link](2,"Grapes"); [Link]("After set(2,Grapes): "+list);
[Link](1,"Pineapple"); [Link]("After add(1,Pineapple): "+list);
[Link]("Orange"); [Link]("After remove Orange: "+list);
[Link](list); [Link]("Sorted: "+list);
[Link](list); [Link]("Reversed: "+list);
[Link]("for-each: ");
for(String f:list) [Link](f+" ");
[Link]();
// Iterator safe removal
Iterator<String> it=[Link]();
while([Link]()){if([Link]().startsWith("A")) [Link]();}
[Link]("After removing A*: "+list);
[Link]("Min: "+[Link](list)+" Max: "+[Link](list));
Object[] arr=[Link]();
[Link]("Array length: "+[Link]);
[Link](); [Link]("After clear: empty="+[Link]());
}
}
8. HashMap demonstration.
import [Link].*;
public class HashMapFull{
public static void main(String[] args){
HashMap<String,Integer> scores=new HashMap<>();
[Link]("Alice",95); [Link]("Bob",87);
[Link]("Charlie",92); [Link]("Diana",88);
[Link]("Map: "+scores);
[Link]("Size: "+[Link]());
[Link]("Alice score: "+[Link]("Alice"));
[Link]("containsKey Bob: "+[Link]("Bob"));
[Link]("containsValue 92: "+[Link](92));
[Link]("Bob",90); // update
[Link]("After update Bob: "+[Link]("Bob"));
[Link]("Diana");
[Link]("After remove Diana: "+scores);
[Link]("Eve",78);
[Link]("After putIfAbsent Eve: "+scores);
[Link]("\n--- Iterating entrySet ---");
for([Link]<String,Integer> e:[Link]())
[Link](" "+[Link]()+" -> "+[Link]());
[Link]("Keys: "+[Link]());
[Link]("Values: "+[Link]());
// Find highest scorer
String top=""; int maxScore=0;
for([Link]<String,Integer> e:[Link]())
if([Link]()>maxScore){maxScore=[Link]();top=[Link]();}
[Link]("Top scorer: "+top+" with "+maxScore);
// Count with getOrDefault
String[] words={"java","python","java","c","java","python"};
HashMap<String,Integer> freq=new HashMap<>();
for(String w:words) [Link](w,[Link](w,0)+1);
[Link]("Word frequencies: "+freq);
}
}
9. Generics demonstration.
import [Link].*;
class Box<T>{T value;
Box(T v){value=v;}
T get(){return value;}
void set(T v){value=v;}
@Override public String toString(){return "Box["+value+"]";}
}
class Pair<A,B>{A first; B second;
Pair(A a,B b){first=a;second=b;}
@Override public String toString(){return "("+first+","+second+")";}
}
class GenUtil{
public static <T extends Comparable<T>> T max(T a,T b){return [Link](b)>=0?a:b;}
public static <T> void swap(T[] arr,int i,int j){T tmp=arr[i];arr[i]=arr[j];arr[j]=tmp;}
public static <T> void print(List<T> list){for(T x:list)[Link](x+"
");[Link]();}
}
public class GenericsDemo{
public static void main(String[] args){
Box<String> sb=new Box<>("Hello"); [Link]("String box: "+sb);
Box<Integer> ib=new Box<>(42); [Link]("Integer box: "+ib);
[Link](99); [Link]("Updated: "+ib);
Pair<String,Integer> p=new Pair<>("Abubakar",19); [Link]("Pair: "+p);
[Link]("Max(10,20): "+[Link](10,20));
[Link]("Max(Apple,Banana): "+[Link]("Apple","Banana"));
Integer[] arr={5,2,8,1,9};
[Link](arr,0,4);
[Link]("After swap: "); for(int x:arr) [Link](x+" ");
[Link]();
List<Integer> nums=[Link](1,2,3,4,5);
List<String> names=[Link]("Alice","Bob","Charlie");
[Link]("Nums: "); [Link](nums);
[Link]("Names: "); [Link](names);
ArrayList<String> typeSafe=new ArrayList<>();
[Link]("Java"); // [Link](42); // COMPILE ERROR - type safety!
[Link]("Type-safe list: "+typeSafe);
}
}
10. JavaBeans demonstration.
import [Link];
class StudentBean implements Serializable{
private static final long serialVersionUID=1L;
private String name; private int age; private double gpa; private String branch;
public StudentBean(){} // required no-arg constructor
public StudentBean(String name,int age,double gpa,String branch){
setName(name); setAge(age); setGpa(gpa); setBranch(branch);
}
// Getters
public String getName(){return name;}
public int getAge(){return age;}
public double getGpa(){return gpa;}
public String getBranch(){return branch;}
// Setters with validation
public void setName(String n){
if(n==null||[Link]().isEmpty()) throw new IllegalArgumentException("Name cannot be
empty");
[Link]=[Link]();
}
public void setAge(int a){
if(a<0||a>150) throw new IllegalArgumentException("Invalid age: "+a);
[Link]=a;
}
public void setGpa(double g){
if(g<0.0||g>10.0) throw new IllegalArgumentException("GPA must be 0-10");
[Link]=g;
}
public void setBranch(String b){[Link]=b;}
public boolean isExcellent(){return gpa>=9.0;}
@Override public String toString(){
return "StudentBean{name='"+name+"',age="+age+",gpa="+gpa+",branch='"+branch+"',excellen
t="+isExcellent()+"}";
}
}
public class JavaBeansDemo{
public static void main(String[] args){
// No-arg constructor + setters (bean pattern)
StudentBean s1=new StudentBean();
[Link]("Abubakar"); [Link](19); [Link](8.7); [Link]("BCA");
[Link](s1);
[Link]("Excellent: "+[Link]());
// Parameterized constructor
StudentBean s2=new StudentBean("Alice",20,9.4,"BCA");
[Link](s2);
// Validation test
try{[Link](-5);}
catch(IllegalArgumentException e){[Link]("Validation: "+[Link]());}
try{[Link](11.0);}
catch(IllegalArgumentException e){[Link]("Validation: "+[Link]());}
// Array of beans
StudentBean[] students={s1,s2,new StudentBean("Bob",21,7.5,"BCA")};
[Link]("\n--- All Students ---");
for(StudentBean s:students)
[Link]("%-12s Age:%-3d GPA:%.1f
%s%n",[Link](),[Link](),[Link](),[Link]()?"***":"");
}
}