Java Programming Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Java
Module 2
Classes, Objects, Inheritance, Interfaces, Strings and I/O Streams
Module 3
Packages, Exception Handling and Multithreading
Module 4
Applets, Graphics and AWT Event Handling
Module 5
Swing Controls and Java Database Connectivity (JDBC)
Read Module Notes Online
Module I: Introduction to Java
Chapter 1: Paradigms of Programming Languages and Object-Oriented Concepts
1.1 Evolution of Programming Paradigms
A programming paradigm represents a fundamental style or methodology of structuring computer programs and reasoning about computation. Over the history of software engineering, programming languages have evolved to manage increasing software complexity, shifting from low-level hardware-centric instructions to high-level abstractions that mirror real-world problem domains. Understanding these paradigms explains why object-oriented programming emerged as the dominant model for large-scale enterprise and desktop systems.
In the monolithic and unstructured paradigm, early programs consisted of sequential machine or assembly instructions with unconditional jumps. As program size grew, control flow became difficult to trace and maintain. This led to the imperative and procedural paradigm (exemplified by C, Pascal, and Fortran), where computation is expressed as a sequence of statements that modify program state through functions or procedures. While procedural decomposition improved code reuse, data remained globally exposed or loosely coupled to procedures, making large multi-developer codebases fragile when data structures changed.
Other important paradigms include the functional paradigm, which models computation as the evaluation of mathematical functions without mutable state; the logic paradigm, which expresses computation as logical relations and inference rules; and the object-oriented paradigm, which unifies data and the operations permitted on that data into self-contained software entities called objects.
In modern software architecture, selecting a paradigm influences coupling (how strongly modules depend on one another) and cohesion (how closely responsibilities inside a single module belong together). Procedural systems often exhibit high coupling when multiple functions manipulate shared global arrays or structures. Object-oriented systems aim for low coupling and high cohesion by restricting state mutations to well-defined object interfaces.
1.2 Basic Concepts of Object-Oriented Programming
Object-Oriented Programming (OOP) organizes software design around data, or objects, rather than isolated functions and logic. Every object models an entity with state (attributes) and behavior (methods). The foundational pillars of OOP are summarized below:
- Class: A user-defined blueprint or template that specifies the data fields (instance variables) and behaviors (methods) common to all objects of a particular kind. A class defines a logical type without allocating memory for instance data until objects are instantiated.
- Object: A runtime instance of a class that occupies memory and holds concrete attribute values. Objects interact with one another by invoking methods, a mechanism conceptually known as message passing.
- Encapsulation: The bundling of data (fields) and the methods that operate on that data into a single unit (class), combined with restricting direct external access to internal state. By declaring fields private and exposing controlled public methods, encapsulation enforces data integrity and hides internal representation details.
- Abstraction: The practice of exposing only essential features and behaviors of an entity while hiding complex underlying implementation details. In Java, abstraction is achieved through abstract classes and interfaces, allowing callers to depend on contracts rather than concrete implementations.
- Inheritance: A mechanism by which a new class (subclass or derived class) acquires the properties and behaviors of an existing class (superclass or base class). Inheritance establishes an is-a relationship, promotes hierarchical classification, and enables code reuse without duplication.
- Polymorphism: The ability of a single interface, method name, or reference variable to take multiple forms depending on the context. Compile-time polymorphism is realized through method overloading, whereas runtime polymorphism is realized through method overriding and dynamic method dispatch.
- Dynamic Binding and Message Passing: Dynamic binding resolves a method call to its concrete implementation at runtime based on the actual object type rather than the reference type. Message passing refers to objects communicating by invoking each other's public methods with arguments.
Consider a banking domain to see these concepts working together: Account is an abstract class defining the contract withdraw(double amount) (abstraction). SavingsAccount and CurrentAccount inherit common fields like accountNumber and balance from Account (inheritance), while keeping balance private and editable only via validated methods (encapsulation). When a teller loop iterates over an array of Account references and calls withdraw(), each object executes its own rule—minimum balance check for savings or overdraft check for current—demonstrating runtime polymorphism.
1.3 Procedure-Oriented Programming vs. Object-Oriented Programming
Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP) differ fundamentally in how they decompose problems, protect data, and scale to complex systems.
| Comparison Dimension | Procedure-Oriented Programming (POP) | Object-Oriented Programming (OOP) |
|---|---|---|
| Primary Focus | Focuses on algorithms, procedures, and step-by-step control flow. | Focuses on objects that bind data and behavior together. |
| Program Decomposition | Decomposes a program into smaller functions or subroutines. | Decomposes a program into interacting classes and objects. |
| Data Security | Global data is shared openly across functions, risking accidental modification. | Data hiding via access specifiers protects internal object state. |
| Design Approach | Follows a top-down design methodology from main routine to sub-routines. | Follows a bottom-up design methodology from core entities to system integration. |
| Extensibility | Adding new data structures often requires modifying many existing functions. | Inheritance and polymorphism allow extending behavior with minimal changes. |
| Code Reusability | Limited to function libraries and copy-paste reuse. | High reusability through inheritance, composition, and interfaces. |
| Representative Languages | C, Pascal, Fortran, COBOL. | Java, C++, C#, Python, Kotlin. |
1.4 Benefits and Applications of OOP
Object-oriented design provides substantial engineering advantages over procedural models:
- Modularity and Maintainability: Clear class boundaries localize faults, making debugging and maintenance predictable even in systems with millions of lines of code.
- Reusability: Existing tested classes can be reused across projects or extended cleanly via inheritance and composition, reducing development time.
- Data Security: Encapsulation prevents unauthorized external code from corrupting object invariants.
- Scalability and Extensibility: Polymorphic interfaces allow new components to be plugged into existing frameworks without rewriting core dispatch logic.
Because of these strengths, OOP is widely applied in enterprise web applications, Android and mobile app development, graphical user interfaces (GUIs), real-time simulation and modeling, banking and financial systems, distributed cloud microservices, and game development.
Chapter 2: Java Fundamentals, JVM, JDK, JRE, and Bytecode
2.1 History and Evolution of Java
Java originated in 1991 at Sun Microsystems as part of the Green Project, led by James Gosling, Patrick Naughton, and Mike Sheridan. Initially named Oak, the language was designed for embedded consumer electronics such as set-top boxes and interactive television controllers, where hardware diversity demanded platform independence and strict reliability. When the World Wide Web gained momentum in the mid-1990s, the team recognized that a portable, secure language could power dynamic web content and networked applications. The language was renamed Java in 1995 and released publicly with the promise of "Write Once, Run Anywhere" (WORA).
Over subsequent decades, Java evolved through major releases managed under the Java Community Process and later Oracle Corporation and OpenJDK. Major milestones include Java 2 (which split the ecosystem into J2SE for desktop, J2EE for enterprise servers, and J2ME for embedded devices), Java 5 (introducing generics, annotations, autoboxing, and enhanced loops), Java 8 (lambda expressions, Stream API, and default interface methods), and Long-Term Support (LTS) releases such as Java 11, Java 17, and Java 21.
2.2 Key Features of Java
The design philosophy of Java is captured by twelve core characteristics, often termed Java buzzwords:
- Simple: Java removes error-prone C/C++ constructs such as explicit pointer arithmetic, operator overloading, and manual memory deallocation, while retaining familiar C-like syntax.
- Object-Oriented: Nearly everything in Java (except primitive types) is modeled as an object inside a class hierarchy rooted at
java.lang.Object. - Platform Independent: Java source code compiles into intermediate bytecode rather than native machine instructions, allowing the same compiled class files to execute on Windows, Linux, or macOS wherever a compatible JVM exists.
- Secured: Programs execute inside the Java Virtual Machine sandbox with bytecode verification, classloader isolation, and no direct memory pointer manipulation, preventing buffer overflows and unauthorized memory access.
- Robust: Strong static type checking at compile time, runtime bounds checking on arrays, structured exception handling, and automatic garbage collection eliminate common memory leaks and crashes.
- Architecture Neutral: Primitive data types have fixed, standardized bit widths across all hardware platforms (for example,
intis always 32 bits), ensuring consistent numerical behavior. - Portable: Combined architecture neutrality and standardized library APIs ensure programs behave identically across platforms without implementation-dependent behavior.
- Interpreted and High Performance: Although bytecode is interpreted by the JVM, modern Just-In-Time (JIT) compilers translate frequently executed bytecode hotspots into native machine code at runtime, achieving near-native execution speed.
- Multithreaded: Java provides built-in language and library support for concurrent execution, thread synchronization, and inter-thread communication.
- Distributed and Dynamic: Built-in networking APIs (
java.net) support TCP/IP, HTTP, and remote method invocation, while dynamic class loading allows linking classes at runtime.
2.3 Java Bytecode, JVM, JRE, and JDK
Java achieves platform independence through a two-stage compilation and execution pipeline. First, the Java compiler (javac) translates human-readable .java source files into platform-neutral Java Bytecode stored in .class files. Bytecode is a compact, stack-oriented instruction set designed specifically for the Java Virtual Machine rather than any physical CPU.
At runtime, the Java Virtual Machine (JVM) loads, verifies, and executes the bytecode. Internally, the JVM consists of three major subsystems:
- ClassLoader Subsystem: Performs Loading (reading binary
.classstreams via Bootstrap, Platform, and Application classloaders), Linking (Verifying bytecode safety, Preparing static fields with default values, and Resolving symbolic references), and Initialization (executing static initializers and assigning static field values). - Runtime Data Areas: Divides memory into the Method Area (class metadata, runtime constant pool, method bytecode), Heap (shared storage for all object instances and arrays, managed by the Garbage Collector), JVM Stacks (per-thread stack frames storing local variables and operand stacks), Program Counter (PC) Registers (tracking current instruction address per thread), and Native Method Stacks (supporting JNI native calls).
- Execution Engine: Executes instructions via the Interpreter (decoding bytecode line by line), the Just-In-Time (JIT) Compiler (compiling hot loops and methods into native machine code for speed), and the Garbage Collector (reclaiming unreferenced heap objects automatically).
The Java Runtime Environment (JRE) bundles the JVM together with the core Java class libraries (such as java.lang, java.util, and java.io) needed to run compiled Java applications. The Java Development Kit (JDK) is a superset of the JRE that adds development tools—including the compiler (javac), archiver (jar), documentation generator (javadoc), and debugger (jdb)—required to write, compile, and package Java software.
| Component | Primary Role | Key Contents | Target Audience |
|---|---|---|---|
| JVM (Java Virtual Machine) | Executes Java bytecode and manages memory. | ClassLoader, Runtime Data Areas, Execution Engine (JIT + GC). | Runtime execution layer on host OS. |
| JRE (Java Runtime Environment) | Provides complete environment to run Java programs. | JVM + Standard Java Class Libraries + Supporting files. | End users running compiled Java applications. |
| JDK (Java Development Kit) | Provides tools to develop, compile, and debug Java code. | JRE + Compiler (javac), Debugger (jdb), jar, javadoc. |
Java software developers and engineers. |
Chapter 3: Java Program Structure, Execution, and Tokens
3.1 Types of Java Programs and Architecture
Java supports two classical categories of programs: Standalone Applications and Applets (alongside modern server-side servlets and microservices). A standalone application executes locally on a machine via the command-line or desktop JVM and requires a public static void main(String[] args) entry point. Here, public allows the JVM to invoke it from outside the class, static allows invocation without instantiating the class, void indicates no return value to the OS, and String[] args receives command-line arguments. An applet is a specialized Java program designed to be embedded inside an HTML page and executed within a web browser or appletviewer, inheriting from java.applet.Applet and following lifecycle callbacks rather than a main method.
A standard Java source file follows a well-defined program structure: an optional Documentation Section (comments describing the module), an optional Package Statement (declaring namespace membership), Import Statements (referencing external classes), optional Interface and Class Definitions, and the Main Method Class whose filename must match the public class name exactly (case-sensitive) with a .java extension.
3.2 Creating, Compiling, and Executing Java Programs
To create and run a Java program, the developer writes source code in a text editor or IDE and saves it as ProgramStructureDemo.java. Compilation is invoked using javac ProgramStructureDemo.java, which checks syntax and type rules and produces ProgramStructureDemo.class containing bytecode. Execution is launched using java ProgramStructureDemo (without the .class extension), which starts the JVM, loads the class, verifies bytecode integrity, and invokes the main method.
Java supports three styles of comments for program documentation: single-line comments starting with //, multi-line block comments enclosed between /* and */, and documentation comments enclosed between /** and */, which the javadoc utility parses into HTML API documentation using tags such as @param, @return, and @author.
/**
* Demonstrates standard Java program structure, comments, and Scanner input.
*/
import java.util.Scanner;
public class ProgramStructureDemo {
// Entry point of standalone Java application
public static void main(String[] args) {
/* Multi-line comment:
Read student details and display formatted summary */
Scanner sc = new Scanner(System.in);
System.out.print("Enter student name: ");
String name = sc.nextLine();
System.out.print("Enter semester number: ");
int sem = sc.nextInt();
System.out.println("Student " + name + " enrolled in Semester " + sem);
sc.close();
}
}3.3 Java Tokens: Keywords, Identifiers, Literals, and Operators
The smallest individual units in a Java source program recognized by the compiler are called tokens. Java defines five categories of tokens: keywords, identifiers, literals, operators, and separators.
- Keywords: Reserved words with predefined syntactic meaning to the compiler (such as
class,public,static,void,int,if,else,while,return,extends,implements). Keywords are always lowercase and cannot be used as variable or class names. Note thattrue,false, andnullare technically literal values rather than keywords, though they are equally reserved. - Identifiers: Programmer-defined names assigned to classes, methods, variables, packages, and interfaces. An identifier may contain Unicode letters, digits, underscores (
_), and dollar signs ($), must not begin with a digit, is case-sensitive (countandCountare distinct), and cannot be a reserved keyword. By convention, class names use PascalCase (StudentRecord), methods and variables use camelCase (totalMarks), and constants use UPPER_SNAKE_CASE (MAX_CAPACITY). - Literals: Constant values written directly in source code, including integer literals (decimal, octal
075, hexadecimal0x4F, binary0b1010, with optional underscores1_000_000), floating-point literals (3.14,2.5f), character literals ('A',' ','A'), string literals ("Kerala"), boolean literals (true,false), and thenullreference literal. - Separators: Symbols that structure code, including parentheses
(), braces{}, brackets[], semicolon;, comma,, and period..
Operators perform computations on one, two, or three operands and are grouped by function and precedence:
| Operator Category | Operators | Purpose and Example |
|---|---|---|
| Arithmetic | +, -, *, /, % |
Basic numeric arithmetic and remainder modulo (e.g., 17 % 5 yields 2). |
| Unary | +, -, ++, --, !, ~ |
Sign inversion, pre/post increment & decrement, logical NOT, bitwise complement. |
| Relational | ==, !=, >, <, >=, <= |
Compares values and returns a boolean result. |
| Logical | &&, ||, ! |
Short-circuit logical AND, OR, and NOT on boolean expressions. |
| Bitwise & Shift | &, |, ^, <<, >>, >>> |
Bit-level manipulation and signed/unsigned bit shifting. |
| Assignment | =, +=, -=, *=, /=, %= |
Assigns or updates variable values in place. |
| Ternary & Type | ? :, instanceof |
Conditional expression evaluation and runtime type checking. |
Understanding operator precedence and associativity prevents subtle bugs. Postfix operators (x++) bind tighter than unary prefix operators (++x), which bind tighter than multiplicative (* / %), additive (+ -), relational (< >), equality (== !=), logical AND (&&), logical OR (||), ternary (? :), and finally assignment (=). All binary arithmetic operators are left-associative, whereas assignment and ternary operators are right-associative.
3.4 Data Types, Variables, Type Conversions, and Expressions
Java is a strongly typed language: every variable and expression has a declared type verified at compile time. Data types fall into two families: primitive types (eight built-in value types) and reference types (classes, interfaces, and arrays).
| Primitive Type | Size (Bits) | Default Value | Value Range / Description |
|---|---|---|---|
byte |
8 bits | 0 |
Signed two's complement integer: -128 to 127. |
short |
16 bits | 0 |
Signed integer: -32,768 to 32,767. |
int |
32 bits | 0 |
Default integer type: -2,147,483,648 to 2,147,483,647. |
long |
64 bits | 0L |
Large integer values suffixed with L. |
float |
32 bits | 0.0f |
Single-precision IEEE 754 floating point. |
double |
64 bits | 0.0d |
Double-precision IEEE 754 floating point (default for decimals). |
char |
16 bits | ' ' |
Unsigned Unicode character: 0 to 65,535. |
boolean |
JVM-dependent | false |
Logical truth values: strictly true or false. |
Variables in Java are classified by scope and lifetime into local variables (declared inside methods/blocks, stored on the JVM stack, must be explicitly initialized before use), instance variables (declared inside a class outside methods, stored on the heap inside each object, receive default values automatically), and static (class) variables (declared with static, stored in class metadata and shared across all instances).
Type conversion occurs in two forms. Widening (implicit) conversion happens automatically when assigning a smaller type to a larger compatible type (byte → short → int → long → float → double) without data loss. Narrowing (explicit) casting converts a larger type to a smaller type using a cast operator such as int x = (int) 9.78;, which truncates the fractional part and requires programmer awareness of potential precision loss. Expressions combine variables, literals, and operators; during arithmetic evaluation, Java automatically promotes byte, short, and char operands to int before computing results.
Chapter 4: Control Structures and Arrays in Java
4.1 Decision-Making Statements
Control structures govern the order in which statements execute. Decision-making (selection) statements allow a program to choose different execution paths based on runtime conditions:
ifandif-else: Executes a block when a boolean condition evaluates totrue, and optionally executes an alternate block whenfalse. Note that Java strictly requires abooleanexpression—integers like1or0are rejected by the compiler.if-else-ifLadder and Nestedif: Evaluates multiple mutually exclusive conditions sequentially from top to bottom, or nests one condition inside another for multi-criteria decisions.switchStatement: Dispatches execution among multiple constantcasebranches based on the value of an expression of typebyte,short,char,int,String, orenum. Abreakstatement prevents fall-through to subsequent cases, whiledefaulthandles unmatched values.
4.2 Iteration Statements and Jump Statements
Iteration statements (loops) repeat a block of code while a condition remains satisfied:
whileLoop: An entry-controlled loop that tests its boolean condition before each iteration; if initiallyfalse, the body executes zero times.do-whileLoop: An exit-controlled loop that executes its body at least once before evaluating the condition at the end of the block.forLoop: Integrates initialization, condition testing, and update expressions in a compact header, ideal when the iteration count is known.- Enhanced
for-eachLoop: Iterates cleanly over every element of an array or collection (for (int val : arr)) without manual index management.
Jump statements alter normal sequential or loop flow: break terminates the enclosing loop or switch immediately (or an outer labeled block when written as break outer;); continue skips the remainder of the current loop iteration and proceeds to the next iteration; and return exits the current method, optionally passing a value back to the caller.
public class ControlFlowDemo {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1: System.out.println("Selected Addition"); break;
case 2: System.out.println("Selected Prime Search"); break;
default: System.out.println("Invalid Choice");
}
// Labeled break example in nested loop search
int[][] grid = { {12, 18, 25}, {30, 42, 55} };
int target = 42;
searchLoop:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == target) {
System.out.println("Found " + target + " at (" + r + "," + c + ")");
break searchLoop;
}
}
}
}
}4.3 Arrays in Java: One-Dimensional and Multi-Dimensional Arrays
An array in Java is a fixed-size, homogeneous container object that stores elements of the same data type in contiguous logical order, indexed from 0 to length - 1. Unlike C/C++, Java arrays are first-class objects allocated dynamically on the heap using new, and every array exposes a read-only length field. Accessing an index outside valid bounds throws an ArrayIndexOutOfBoundsException at runtime.
Defining, Initializing, and Accessing a 1D Array: An array reference is declared as int[] marks; (preferred) or int marks[];, instantiated via marks = new int[5];, or initialized inline via int[] marks = {85, 90, 78, 92, 88};. Elements are read or modified using bracket indexing such as marks[0]. Common 1D array algorithms include linear search, finding maximum/minimum values, and bubble or selection sorting.
Multi-Dimensional Arrays: Java represents multi-dimensional arrays as arrays of arrays. A two-dimensional array int[][] matrix = new int[3][3]; creates 3 row references, each pointing to a 3-element integer array. Because rows are independent array objects, Java also supports jagged (ragged) arrays where different rows have different lengths (for example, row 0 has 2 columns and row 1 has 4 columns).
public class MatrixAndJaggedDemo {
public static void main(String[] args) {
int[][] a = { {1, 2, 3}, {4, 5, 6} }; // 2x3 matrix
int[][] b = { {7, 8}, {9, 10}, {11, 12} }; // 3x2 matrix
int[][] product = new int[a.length][b[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b[0].length; j++) {
for (int k = 0; k < a[0].length; k++) {
product[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.println("Resultant 2x2 Matrix:");
for (int[] row : product) {
for (int val : row) System.out.print(val + "\t");
System.out.println();
}
// Jagged array with varying row lengths
int[][] jagged = new int[3][];
jagged[0] = new int[] {10, 20};
jagged[1] = new int[] {30, 40, 50};
jagged[2] = new int[] {60};
System.out.println("Jagged row 1 length: " + jagged[1].length);
}
}Chapter 5: Applied Array Algorithms, Command-Line Arguments, and Type Promotion
5.1 Command-Line Arguments in Java
Every standalone Java application begins execution at public static void main(String[] args). The args parameter is a one-dimensional array of String objects populated by the Java Virtual Machine from whitespace-separated tokens supplied after the class name on the command line. Because command-line arguments always arrive as text strings, numeric values must be explicitly parsed using wrapper class methods such as Integer.parseInt(args[0]) or Double.parseDouble(args[1]). Attempting to index args without checking args.length first can trigger an ArrayIndexOutOfBoundsException, while passing non-numeric text to parseInt throws a NumberFormatException.
5.2 Operator Precedence, Type Promotion, and Casting
When evaluating mixed-type expressions in Java, the compiler enforces strict binary numeric promotion rules to prevent silent data loss:
- All
byte,short, andcharoperands are automatically promoted tointbefore arithmetic operations are performed. - If either operand is
long, the other is promoted tolong; if either isfloat, the other becomesfloat; and if either isdouble, the entire expression evaluates todouble. - Assigning a wider type back into a narrower variable (for example, storing an
intresult into abyteor adoubleinto anint) requires an explicit cast operator such as(int) value, which truncates any fractional component.
| Precedence Level | Operators | Category | Associativity |
|---|---|---|---|
| 1 (Highest) | ++, -- (postfix), (), [], . |
Postfix & Member Access | Left to Right |
| 2 | ++, -- (prefix), +, -, !, ~, (type) |
Unary & Cast | Right to Left |
| 3 | *, /, % |
Multiplicative | Left to Right |
| 4 | +, - |
Additive | Left to Right |
| 5 | <<, >>, >>> |
Shift Operators | Left to Right |
| 6 | <, <=, >, >=, instanceof |
Relational | Left to Right |
| 7 | ==, != |
Equality | Left to Right |
| 8 | && followed by || |
Logical Short-Circuit | Left to Right |
| 9 | ?: |
Ternary Conditional | Right to Left |
| 10 (Lowest) | =, +=, -=, *=, /= |
Assignment | Right to Left |
5.3 Searching, Sorting, and Matrix Operations
Arrays serve as the foundation for classical searching, sorting, and linear-algebraic computations. Linear search scans elements sequentially in time and works on unsorted arrays, whereas binary search halves the search interval repeatedly in time on sorted arrays. Bubble sort repeatedly swaps adjacent out-of-order elements in time. Two-dimensional arrays model matrices where element in matrix addition equals and transpose swaps row and column indices ().
public class ArrayAlgorithmsDemo {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
public static int binarySearch(int[] sorted, int target) {
int low = 0, high = sorted.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (sorted[mid] == target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] result = new int[cols][rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
result[c][r] = matrix[r][c];
}
}
return result;
}
public static void main(String[] args) {
int[] marks = {72, 91, 58, 84, 65};
bubbleSort(marks);
int idx = binarySearch(marks, 84);
System.out.println("84 found at sorted index: " + idx);
int[][] mat = {{1, 2, 3}, {4, 5, 6}};
int[][] t = transpose(mat);
System.out.println("Transposed dimensions: " + t.length + "x" + t[0].length);
}
}Module II: Classes, Objects, Inheritance, Interfaces, Strings and I/O Streams
Chapter 1: Classes, Objects, Methods, and Constructors
1.1 Class Fundamentals and Object Creation
In Java, a class serves as the fundamental unit of encapsulation, combining state (fields) and behavior (methods) into a reusable blueprint. A class declaration begins with optional modifiers (such as public), the keyword class, the class identifier, and a body enclosed in braces. Creating an object from a class involves three distinct steps: declaration of a reference variable on the stack (Student s;), instantiation using the new operator which allocates memory for instance fields on the heap, and initialization by invoking a constructor (s = new Student();).
When an object is created, its reference variable holds a handle to the heap memory block. Multiple reference variables can point to the exact same heap object (aliasing), and if a reference variable is assigned null, it no longer refers to any object. Once an object becomes unreachable from all live references, it becomes eligible for automatic reclamation by the JVM Garbage Collector.
1.2 Instance Members vs. Static Members
Members declared inside a class are either instance members or static members:
- Instance Variables and Instance Methods: Belong to each individual object. Every object maintains its own independent copy of instance fields, accessed via an object reference (
s.name). Instance methods can access both instance members and static members directly. - Static Variables (Class Variables): Declared with the
statickeyword. Only a single copy exists in memory, shared across all objects of that class. They are initialized once when the class is loaded by the ClassLoader. - Static Methods and Static Blocks: Static methods belong to the class rather than any object and can be invoked using the class name (
Math.sqrt(25)). A static method cannot access instance variables or invoke instance methods directly without an object reference, and cannot usethisorsuper. Astatic { ... }initialization block runs once when the class is first loaded, useful for complex static setup.
1.3 Defining Methods, Method Overloading, and Argument Passing
A method defines a named block of executable code with a return type, parameter list, and body. Method overloading allows a class to define multiple methods with the same name provided their parameter lists differ in number, data types, or order of parameters. Return type alone cannot distinguish overloaded methods because callers can ignore return values. Overloading implements compile-time (static) polymorphism, because the compiler selects the matching method signature during compilation.
Java strictly uses pass-by-value for all argument passing. When a primitive variable is passed to a method, a copy of its bit value is transmitted; modifying the parameter inside the method does not affect the caller's original variable. When an object reference is passed, Java copies the reference value (the memory address) into the parameter. Consequently, both the caller's variable and the method parameter point to the same heap object: mutating the object's fields inside the method is visible to the caller, whereas reassigning the parameter to a brand-new object does not alter the caller's reference.
class Box {
int width;
Box(int w) { this.width = w; }
}
public class ArgumentPassingDemo {
static void modifyPrimitive(int x) {
x = x + 50; // Changes only local copy
}
static void modifyObjectState(Box b) {
b.width = 99; // Mutates shared heap object
}
static void reassignReference(Box b) {
b = new Box(500); // Reassigns local reference copy only
}
public static void main(String[] args) {
int num = 10;
modifyPrimitive(num);
System.out.println("Primitive after call: " + num); // 10
Box myBox = new Box(20);
modifyObjectState(myBox);
System.out.println("Object width after mutation: " + myBox.width); // 99
reassignReference(myBox);
System.out.println("Object width after reassign: " + myBox.width); // Still 99
}
}1.4 Constructors, this Keyword, and finalize()
A constructor is a special block of code invoked automatically when an object is created with new. It carries the exact same name as its class and has no return type (not even void). If a programmer defines no constructor, the Java compiler synthesizes a public no-argument default constructor that initializes fields to their type defaults (0, false, null). Programmers commonly define parameterized constructors to initialize fields with caller-supplied values, copy constructors to clone another object's state, and use constructor overloading to provide multiple ways of constructing an object.
The this keyword refers to the current object instance. It resolves naming conflicts between instance fields and parameters (this.id = id;), passes the current object as an argument to another method, and enables constructor chaining via this(...) as the very first statement inside another constructor.
Memory occupied by unreferenced objects on the heap is reclaimed automatically by the Garbage Collector. Historically, classes could override the protected finalize() method (inherited from Object) to perform cleanup immediately before garbage collection; however, because finalization timing is unpredictable, can resurrect dead objects, and introduces performance overhead, finalize() is deprecated in modern Java in favor of try-with-resources and AutoCloseable.
public class BankAccount {
private String accountHolder;
private double balance;
private static int totalAccounts = 0;
static {
System.out.println("BankAccount class initialized.");
}
public BankAccount() {
this("Unnamed", 0.0); // Constructor chaining
}
public BankAccount(String accountHolder, double initialDeposit) {
this.accountHolder = accountHolder;
this.balance = initialDeposit;
totalAccounts++;
}
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public void deposit(double amount, String note) {
deposit(amount);
System.out.println("Deposited " + amount + " (" + note + ")");
}
public static int getTotalAccounts() { return totalAccounts; }
public void display() {
System.out.println(accountHolder + " -> Balance: " + balance);
}
}Chapter 2: Inheritance, Polymorphism, and Visibility Control
2.1 Defining Inheritance and Types of Inheritance
Inheritance allows a subclass (child/derived class) to derive non-private fields and methods from a superclass (parent/base class) using the extends keyword. Inheritance models an is-a relationship and eliminates duplicate code across related domain entities. Java supports the following inheritance structures for classes:
- Single Inheritance: One subclass inherits from one superclass (e.g.,
class Dog extends Animal). - Multilevel Inheritance: A chain of inheritance where class C extends class B, and class B extends class A (e.g.,
ElectricCar → Car → Vehicle). - Hierarchical Inheritance: Multiple subclasses inherit from a single shared superclass (e.g.,
Circle,Rectangle, andTriangleall extendShape).
Java deliberately forbids multiple inheritance of classes (one class extending two classes simultaneously) to avoid the Diamond Problem, where ambiguity arises if two parent classes define conflicting implementations or state for the same method. Multiple inheritance of behavior contracts is instead achieved safely through interfaces. Note that constructors are not inherited by subclasses, though a subclass constructor always invokes a superclass constructor.
2.2 Method Overriding, Dynamic Method Dispatch, and super
Method overriding occurs when a subclass provides a specific implementation for an instance method already defined in its superclass with the exact same name, parameter list, and compatible (covariant) return type. The overriding method cannot assign a weaker access modifier than the parent method (e.g., a public parent method cannot be overridden as private), and static or private methods cannot be overridden because they are bound at compile time.
When an overridden method is invoked through a superclass reference pointing to a subclass object (e.g., Shape s = new Circle(); s.draw();), the JVM resolves the call at runtime based on the actual object type on the heap rather than the reference variable type. This mechanism is called Dynamic Method Dispatch or runtime polymorphism.
The super keyword provides explicit access to the immediate parent class in three situations:
- Accessing Hidden Fields:
super.ratereads the parent's field when shadowed by a child field of the same name. - Invoking Overridden Methods:
super.display()calls the parent version of an overridden method from within the child's override. - Chaining Constructors:
super(args)invokes a specific parent constructor and must be the very first statement inside the subclass constructor. If omitted, the compiler insertssuper()automatically.
2.3 final Keyword, Abstract Classes, and Visibility Control
The final modifier restricts extensibility and mutability in three contexts: a final variable is a constant whose value cannot be reassigned once initialized (a blank final variable must be initialized in every constructor); a final method cannot be overridden by any subclass, guaranteeing invariant security or algorithmic behavior; and a final class (such as java.lang.String or java.lang.Math) cannot be subclassed at all.
An abstract class (declared with abstract class) cannot be instantiated directly with new and serves as a partial base template. It may contain fields, constructors, concrete methods with bodies, and abstract methods declared without implementation (abstract double area();). Any concrete subclass extending an abstract class must override and implement all inherited abstract methods, or else be declared abstract itself.
abstract class Employee {
protected String name;
public Employee(String name) { this.name = name; }
public abstract double calculatePay();
public void printSlip() {
System.out.println("Employee: " + name + " | Pay: " + calculatePay());
}
}
class SalariedEmployee extends Employee {
protected double baseSalary;
public SalariedEmployee(String name, double baseSalary) {
super(name);
this.baseSalary = baseSalary;
}
@Override
public double calculatePay() { return baseSalary; }
}
class Manager extends SalariedEmployee {
private double bonus;
public Manager(String name, double baseSalary, double bonus) {
super(name, baseSalary);
this.bonus = bonus;
}
@Override
public double calculatePay() {
return super.calculatePay() + bonus; // Calls parent implementation
}
}Visibility Control (Access Modifiers): Java enforces encapsulation and modular boundaries using four visibility levels across classes, packages, and subclasses:
| Access Modifier | Same Class | Same Package | Subclass (Other Package) | Non-Subclass (Other Package) |
|---|---|---|---|---|
private |
Yes | No | No | No |
| Default (package-private) | Yes | Yes | No | No |
protected |
Yes | Yes | Yes | No |
public |
Yes | Yes | Yes | Yes |
Chapter 3: Interfaces and String Handling
3.1 Defining, Extending, and Implementing Interfaces
An interface in Java is a purely abstract contract specifying what a class must do without dictating how it does it. Declared with the interface keyword, an interface contains abstract method signatures, constant variables, and (since Java 8) optional default and static methods. All variables declared inside an interface are implicitly public static final constants, and all non-default/non-static methods are implicitly public abstract.
A class adopts an interface using the implements keyword and must provide public implementations for all abstract methods declared in the interface. A single class can implement multiple interfaces separated by commas (class SmartPrinter implements Printable, Scannable), achieving multiple inheritance of type cleanly. Furthermore, an interface can inherit from one or more parent interfaces using the extends keyword (interface AdvancedPlayer extends AudioPlayer, VideoPlayer). Interface constants are accessed cleanly using the interface name (Printable.MAX_COPIES).
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can contain both abstract and concrete methods. | Abstract methods by default; supports default and static methods. |
| Variables | Can have instance, static, final, or non-final fields. | Variables are implicitly public static final constants. |
| Multiple Inheritance | A class can extend only one abstract class. | A class can implement multiple interfaces simultaneously. |
| Constructors | Can define constructors invoked by subclass super(). |
Cannot have constructors. |
| Design Intent | Models an is-a relationship with shared state. | Models a can-do capability contract across unrelated classes. |
interface Printable {
int MAX_COPIES = 100; // Implicitly public static final
void print(String doc);
}
interface Scannable {
String scan();
}
interface MultiFunctionDevice extends Printable, Scannable {
default void status() {
System.out.println("Device ready. Max copies: " + MAX_COPIES);
}
}
public class OfficePrinter implements MultiFunctionDevice {
@Override
public void print(String doc) { System.out.println("Printing: " + doc); }
@Override
public String scan() { return "Scanned PDF bytes"; }
public static void main(String[] args) {
OfficePrinter op = new OfficePrinter();
op.status();
op.print("BCA_Report.pdf");
}
}3.2 The String Class, Immutability, and Core Methods
In Java, text is represented by objects of the java.lang.String class rather than null-terminated character arrays. A defining characteristic of String is immutability: once a String object is created, its internal character array cannot be modified. Operations such as concatenation, replacement, or case conversion construct and return a brand-new String object. Immutability enables thread safety, prevents tampering with sensitive parameters (such as database URLs and file paths), allows safe hashcode caching in hash tables, and enables memory optimization through the String Constant Pool inside the heap, where identical string literals share a single instance.
When creating strings, String s1 = "Java"; checks the String Constant Pool and reuses any existing literal, whereas String s2 = new String("Java"); explicitly allocates a distinct object on the general heap. Consequently, == compares object references while equals() compares actual character contents.
| Method Signature | Behavior and Return Value | Example |
|---|---|---|
length() |
Returns total character count (int). |
"Java".length() → 4 |
charAt(int index) |
Returns character at zero-based index. | "Java".charAt(1) → 'a' |
substring(int begin, int end) |
Extracts slice from begin (inclusive) to end (exclusive). |
"Kerala".substring(0, 3) → "Ker" |
equals(Object o) / equalsIgnoreCase(String) |
Checks character-by-character content equality. | "BCA".equalsIgnoreCase("bca") → true |
compareTo(String s) |
Lexicographical comparison returning <0, 0, or >0. |
"A".compareTo("C") → -2 |
indexOf(String sub) / contains(s) |
Finds first index of substring (or -1) / boolean membership. | "Java".indexOf("va") → 2 |
trim() / replace(old, new) / split(regex) |
Removes outer whitespace, substitutes chars, or tokenizes into String[]. |
"a,b,c".split(",") → ["a","b","c"] |
When heavy in-place string concatenation is required inside loops, Java provides mutable alternatives: StringBuilder (fast, non-synchronized, preferred for single-threaded code) and StringBuffer (thread-safe, synchronized methods).
Chapter 4: File Handling and Java I/O Streams
4.1 The File Class and Concept of Streams
The java.io.File class provides an abstract representation of file and directory pathnames. It does not read or write file contents directly; instead, it inspects and manages filesystem metadata via methods such as exists(), isFile(), isDirectory(), length(), getAbsolutePath(), createNewFile(), mkdir(), listFiles(), and delete().
Actual data transfer in Java is modeled as a Stream—an ordered sequence of data flowing from a source (input stream) to a destination (output stream). Stream-based I/O offers major advantages: it decouples program logic from physical device details (files, network sockets, memory buffers, or console), supports composable filtering/buffering decorators, and handles sequential data uniformly. By default, java.lang.System opens three standard streams: System.in (standard input, InputStream), System.out (standard output, PrintStream), and System.err (standard error, PrintStream).
4.2 Byte Streams vs. Character Streams
Java's java.io package organizes stream classes into two parallel hierarchies:
| Characteristic | Byte Streams | Character Streams |
|---|---|---|
| Unit of Transfer | Raw 8-bit bytes. | 16-bit Unicode characters. |
| Root Abstract Classes | InputStream and OutputStream. |
Reader and Writer. |
| Primary File Classes | FileInputStream, FileOutputStream. |
FileReader, FileWriter. |
| Buffered Wrappers | BufferedInputStream, BufferedOutputStream. |
BufferedReader (with readLine()), BufferedWriter. |
| Specialized Streams | DataInputStream, DataOutputStream, ObjectInputStream. |
PrintWriter, InputStreamReader, OutputStreamWriter. |
| Ideal Use Case | Binary files: images, audio, video, compiled classes, serialized objects. | Text files: source code, CSV, JSON, configuration, and localized text. |
Using buffered wrappers such as BufferedReader around FileReader dramatically reduces expensive operating system disk calls by reading large chunks into an internal memory buffer. Always closing streams—preferably using a try-with-resources block—prevents file descriptor leaks and flushes buffered output cleanly.
import java.io.*;
public class StreamOperationsDemo {
public static void inspectFile(String path) {
File f = new File(path);
System.out.println("Exists: " + f.exists() + ", Size: " + f.length() + " bytes");
}
// Byte stream binary copy
public static void copyBinaryFile(String src, String dest) throws IOException {
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
// Character stream line-by-line text reader and writer
public static void copyUpperText(String src, String dest) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(src));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(dest)))) {
String line;
while ((line = br.readLine()) != null) {
pw.println(line.toUpperCase());
}
}
}
}Chapter 5: Polymorphism, String Mutability, and Stream Persistence
5.1 Compile-Time vs. Runtime Polymorphism and Type Casting
Polymorphism allows a single uniform interface to represent multiple concrete behaviors. In Java, compile-time polymorphism (static binding) occurs when overloaded methods share the same name with distinct parameter signatures, allowing the compiler to select the exact target at build time. Conversely, runtime polymorphism (dynamic method dispatch) occurs when a superclass reference points to a subclass object and invokes an overridden method; the JVM inspects the actual runtime object on the heap to dispatch the subclass implementation.
When working with inheritance hierarchies, assigning a subclass object to a superclass reference is called upcasting and occurs implicitly because every subclass satisfies the is-a contract of its parent. Converting a superclass reference back to a subclass type is called downcasting and requires an explicit cast guarded by the instanceof operator to avoid a ClassCastException at runtime.
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Binding Time | Resolved at compile time (Static Binding). | Resolved at runtime via JVM vtable (Dynamic Dispatch). |
| Class Scope | Occurs within the same class or between parent and child. | Strictly occurs between a superclass and its subclass. |
| Method Signature | Must differ in parameter count, types, or order. | Must have identical name and parameter list. |
| Return Type | May differ if parameter list differs. | Must be identical or a covariant subtype. |
| Static / Final / Private | Static, final, and private methods can be overloaded. | Static, final, and private methods cannot be overridden. |
5.2 String, StringBuffer, and StringBuilder Comparison
Because java.lang.String objects are immutable, concatenating strings inside a loop with the + operator repeatedly allocates and discards intermediate String instances on the heap, degrading performance to time. For iterative string construction, Java provides two mutable character-buffer classes: StringBuffer and StringBuilder.
| Attribute | String |
StringBuffer |
StringBuilder |
|---|---|---|---|
| Mutability | Immutable (state cannot change after creation). | Mutable (in-place character array resizing). | Mutable (in-place character array resizing). |
| Thread Safety | Thread-safe due to immutability. | Thread-safe (methods are synchronized). |
Not synchronized (single-thread use). |
| Performance | Slow for frequent concatenation loops. | Moderate (lock acquisition overhead). | Fastest for local string assembly. |
| Memory Pool | Literals stored in String Constant Pool. | Stored solely in general JVM Heap. | Stored solely in general JVM Heap. |
abstract class Notification {
public abstract void send(String recipient, String message);
}
class EmailNotification extends Notification {
@Override
public void send(String recipient, String message) {
System.out.println("Email to " + recipient + ": " + message);
}
}
class SmsNotification extends Notification {
@Override
public void send(String recipient, String message) {
System.out.println("SMS to " + recipient + ": " + message);
}
}
public class StringComparisonDemo {
public static String buildReport(String[] items) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.length; i++) {
sb.append(i + 1).append(". ").append(items[i]).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
String[] topics = {"Classes", "Inheritance", "Interfaces", "Streams"};
String report = buildReport(topics);
Notification n = new EmailNotification(); // Upcasting
if (n instanceof EmailNotification) {
n.send("[email protected]", report);
}
n = new SmsNotification();
n.send("+919876543210", "Module II study report ready.");
}
}5.3 Structured Binary Streams and Object Serialization
Beyond raw byte and character streams, Java's java.io package provides higher-level decorator streams that wrap underlying file streams to read and write primitive types or entire object graphs. DataOutputStream and DataInputStream read and write Java primitives (int, double, boolean, UTF strings) in a machine-independent binary format. ObjectOutputStream and ObjectInputStream serialize entire Java objects whose classes implement the marker interface java.io.Serializable, automatically converting object fields into a byte stream for disk storage or network transmission.
Fields marked with the transient keyword (such as temporary caches or sensitive passwords) are excluded from serialization and restored to default zero or null-reference values upon deserialization. Defining a private static final long serialVersionUID ensures version compatibility between serialized files and evolving class definitions.
| Stream Class | Stream Family | Primary Purpose |
|---|---|---|
FileInputStream / FileOutputStream |
Byte Stream | Unbuffered raw 8-bit binary file reading and writing. |
BufferedInputStream / BufferedOutputStream |
Byte Stream | Adds an internal memory buffer to minimize OS disk I/O system calls. |
DataInputStream / DataOutputStream |
Byte Stream | Reads and writes primitive data types in portable binary form. |
ObjectInputStream / ObjectOutputStream |
Byte Stream | Serializes and deserializes Serializable object graphs. |
FileReader / FileWriter |
Character Stream | Reads and writes 16-bit Unicode text files using platform encoding. |
BufferedReader / PrintWriter |
Character Stream | Provides line-oriented readLine() and formatted text output. |
import java.io.*;
class StudentRecord implements Serializable {
private static final long serialVersionUID = 1L;
private int rollNo;
private String name;
private double cgpa;
private transient String sessionToken;
public StudentRecord(int rollNo, String name, double cgpa, String sessionToken) {
this.rollNo = rollNo;
this.name = name;
this.cgpa = cgpa;
this.sessionToken = sessionToken;
}
@Override
public String toString() {
return "Roll=" + rollNo + ", Name=" + name + ", CGPA=" + cgpa;
}
}
public class StudentFilePersistence {
public static void main(String[] args) throws IOException, ClassNotFoundException {
String path = "student_record.ser";
StudentRecord outRec = new StudentRecord(101, "Ananya Nair", 9.15, "TMP-998");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
oos.writeObject(outRec);
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
StudentRecord inRec = (StudentRecord) ois.readObject();
System.out.println("Restored Record: " + inRec);
}
}
}Module III: Packages, Exception Handling and Multithreading
Chapter 1: Packages in Java
1.1 Purpose of Packages and Java API Packages
As software grows into dozens or hundreds of classes, placing all classes in a single default namespace causes naming collisions and poor organization. A package in Java is a namespace mechanism that groups related classes, interfaces, and sub-packages into a hierarchical directory structure. Packages provide three primary benefits: they prevent naming conflicts (for instance, java.util.Date and java.sql.Date coexist cleanly in different packages), they enable controlled access protection via package-private and protected visibility, and they simplify modular distribution in JAR archives.
The Java Standard Edition API itself is organized into well-known built-in packages:
| Java API Package | Core Responsibility | Representative Classes / Interfaces |
|---|---|---|
java.lang |
Fundamental language classes (imported automatically). | Object, String, Math, System, Thread, Exception. |
java.util |
Collections, dates, random numbers, and utility classes. | ArrayList, HashMap, Scanner, Collections, Comparator. |
java.io |
File system access and byte/character stream I/O. | File, FileInputStream, BufferedReader, PrintWriter. |
java.awt / javax.swing |
Graphical User Interface components and event handling. | Frame, Button, JFrame, JButton, JLabel. |
java.sql |
Database connectivity and SQL execution APIs. | DriverManager, Connection, Statement, ResultSet. |
java.net |
Network programming with sockets and URLs. | Socket, ServerSocket, URL, HttpURLConnection. |
1.2 Creating, Accessing, and Extending User-Defined Packages
To place a class into a user-defined package, the very first non-comment statement in the .java file must be package packagename; (or nested hierarchy package university.bca.utils;). Note that Java packages map directly to filesystem directories: the package university.bca.utils corresponds to the folder path university/bca/utils/. When compiling with javac -d . MyClass.java, the -d flag instructs the compiler to create the matching directory hierarchy automatically and place the compiled .class file inside it.
Classes inside a package can be accessed from external code in three ways:
- Single-Class Import:
import university.bca.utils.Calculator;brings onlyCalculatorinto scope and is preferred for clarity. - Wildcard Import:
import university.bca.utils.*;makes all public classes in that package directly accessible (does not import sub-packages recursively). - Fully Qualified Name: Referencing
university.bca.utils.Calculatordirectly in code without animportstatement, essential when disambiguating two classes with the same simple name.
To add another class to an existing package, simply create a new source file with the exact same package declaration at the top and compile it into the same target root directory using javac -d . NewClass.java. The JVM locates package directories at runtime using the CLASSPATH environment variable or the -cp command-line option.
1.3 Hiding Classes Inside a Package and Static Imports
Hiding Classes inside a Package: When a class inside a package is declared without the public modifier (package-private visibility), it is visible only to other classes within the exact same package and completely hidden from external packages. Attempting to import or instantiate a non-public class from another package triggers a compile-time error, allowing library authors to expose clean public facades while concealing internal helper classes and algorithms.
Additionally, Java supports import static java.lang.Math.*; to import static constants (PI) and static methods (sqrt) directly without prefixing the class name.
// File 1: Helper class hidden inside package (no public modifier)
package college.finance;
class TaxHelper {
static double computeTax(double amount) {
return amount * 0.05;
}
}
// File 2: Public facade exposed to external packages
package college.finance;
public class FeeCalculator {
public double calculateTotal(double tuition) {
return tuition + TaxHelper.computeTax(tuition);
}
}
// File 3: External consumer in another package
package college.app;
import college.finance.FeeCalculator;
public class MainApp {
public static void main(String[] args) {
FeeCalculator calc = new FeeCalculator();
System.out.println("Total Fee: " + calc.calculateTotal(12000));
// TaxHelper is hidden here and cannot be imported!
}
}Chapter 2: Exception Handling in Java
2.1 Types of Errors and Advantages of Exception Handling
Software errors fall into three broad categories: compile-time errors (syntax mistakes, missing semicolons, undeclared variables, or type mismatches caught by javac), runtime errors (abnormal events during execution such as division by zero, null pointer dereference, or missing files), and logical errors (program runs without crashing but produces incorrect output due to flawed algorithms). Exception handling specifically addresses runtime errors.
Traditional procedural languages returned integer error codes from functions, forcing callers to clutter business logic with repetitive status checks. Java's structured exception handling separates normal execution logic from error-recovery logic, propagates errors cleanly up the call stack, groups related error types into class hierarchies, and prevents abrupt application termination.
2.2 The Throwable Hierarchy: Checked vs. Unchecked Exceptions
Every exception or error in Java inherits from java.lang.Throwable, which splits into two direct subclasses: Error (serious system-level failures such as OutOfMemoryError or StackOverflowError that applications should not attempt to catch) and Exception (recoverable conditions that applications can anticipate and handle).
| Category | Checked Exceptions | Unchecked (Runtime) Exceptions |
|---|---|---|
| Base Class | Direct subclasses of Exception (excluding RuntimeException). |
Subclasses of RuntimeException (and Error). |
| Compiler Enforcement | Must be caught with try-catch or declared with throws. |
Not checked at compile time; optional handling. |
| Typical Cause | External environment issues: missing files, network drops, SQL errors. | Programming bugs: null dereference, out-of-bounds index, divide by zero. |
| Examples | IOException, SQLException, ClassNotFoundException. |
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException. |
2.3 try, catch, throw, throws, finally, and Custom Exceptions
Java provides five keywords to manage exceptions deterministically:
tryBlock: Encloses statements that might throw an exception. Atryblock must be followed by at least onecatchblock, afinallyblock, or both. Try blocks may also be nested when an inner operation requires specialized recovery before outer handling.catchBlock: Follows atryblock and specifies the exception type it handles. Multiplecatchblocks may handle distinct exception classes, ordered strictly from most specific subclass to most general superclass (e.g.,FileNotFoundExceptionbeforeIOException). Multi-catch syntax (catch (IOException | SQLException e)) handles unrelated exceptions in one block.throwKeyword: Used inside a method body to explicitly construct and throw an exception object (throw new IllegalArgumentException("Negative age");).throwsClause: Appears in a method signature to declare checked exceptions that the method does not handle locally and delegates up the call stack to its caller.finallyStatement: Defines a guaranteed cleanup block that executes whether an exception occurred, was caught, or was not thrown at all—ideal for releasing locks or closing connections. (Only callingSystem.exit()or a fatal JVM crash bypassesfinally.)
Developers can define custom (user-defined) exceptions by extending Exception (for checked exceptions) or RuntimeException (for unchecked exceptions) and passing descriptive error messages to super(message).
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String msg) {
super(msg);
}
}
public class WalletService {
private double balance = 500.0;
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal must be positive.");
}
if (amount > balance) {
throw new InsufficientBalanceException("Shortfall of " + (amount - balance));
}
balance -= amount;
System.out.println("Withdrawn: " + amount + ", Remaining: " + balance);
}
public static void main(String[] args) {
WalletService ws = new WalletService();
try {
ws.withdraw(750.0);
} catch (InsufficientBalanceException e) {
System.out.println("Transaction failed: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Invalid input: " + e.getMessage());
} finally {
System.out.println("Audit log closed.");
}
}
}Chapter 3: Multithreading and Thread Lifecycle
3.1 Creating and Running Threads: Thread vs. Runnable
Multithreading enables a single Java program to execute multiple independent paths of control concurrently, maximizing CPU utilization and keeping user interfaces responsive during background I/O. Unlike heavyweight operating system processes that maintain isolated memory spaces, threads within the same JVM share the heap and method area while keeping private call stacks and program counters.
Java supports two ways to define a thread:
- Extending
java.lang.Thread: Create a subclass ofThread, override itspublic void run()method, instantiate the subclass, and invokestart(). - Implementing
java.lang.Runnable: Implement the functional interfaceRunnableby definingrun(), pass the instance tonew Thread(runnableObj), and invokestart(). ImplementingRunnableis generally preferred because Java allows only single class inheritance—extendingThreadprevents extending any other domain class, whereas implementingRunnablecleanly separates the task from the thread execution mechanism.
A critical rule is to always call start() rather than calling run() directly: start() registers a new OS/JVM execution thread and invokes run() asynchronously, whereas calling run() directly executes the method synchronously on the caller's thread.
3.2 Life Cycle of a Thread
Throughout its execution, a Java thread transitions across well-defined lifecycle states (Thread.State):
| Thread State | Meaning and Trigger | Transition Out |
|---|---|---|
NEW |
Thread object instantiated via new Thread(...); start() not yet called. |
Calling start() moves it to RUNNABLE. |
RUNNABLE |
Eligible for CPU scheduling or actively executing run() on a CPU core. |
Completes run(), blocks on lock, or waits/sleeps. |
BLOCKED |
Waiting to acquire an intrinsic monitor lock held by another thread. | Acquires lock and returns to RUNNABLE. |
WAITING |
Paused indefinitely via Object.wait() or Thread.join(). |
notify() / notifyAll() or target thread finishes. |
TIMED_WAITING |
Paused for a bounded duration via Thread.sleep(ms) or join(ms). |
Timer expires or thread is interrupted. |
TERMINATED |
run() completed normally or exited due to an uncaught exception. |
Final state; a terminated thread cannot be restarted. |
3.3 Thread Methods and Thread Priority
Key control methods on Thread include currentThread() (returns reference to the executing thread), getName() / setName(String), sleep(long millis) (pauses current thread without releasing locks), join() (causes calling thread to wait until target thread finishes), yield() (hints scheduler to pause current thread), interrupt() (sets interrupt flag to wake sleeping/waiting threads cleanly), and isAlive(). Each thread carries a numeric priority from Thread.MIN_PRIORITY (1) through Thread.NORM_PRIORITY (5, default) up to Thread.MAX_PRIORITY (10), configured via setPriority(int) and inspected via getPriority(). Higher-priority threads generally receive scheduling preference, though exact behavior depends on the host OS scheduler.
Chapter 4: Thread Synchronization and Inter-Thread Communication
4.1 Race Conditions, synchronized, and Deadlock
When multiple threads read and modify shared mutable state concurrently without coordination, interleaving operations can corrupt data—a defect known as a race condition. For example, a compound operation such as balance = balance - amount involves reading, subtracting, and writing back; if two threads interleave between read and write, one update is lost.
Java prevents race conditions through synchronization built on intrinsic monitor locks associated with every object. Marking an instance method with synchronized acquires the lock on this before entering the method and releases it automatically upon exit or exception. Alternatively, a synchronized block (synchronized(lockObject) { ... }) narrows locking strictly to the critical section, improving concurrency. For static shared data, a synchronized static method locks on the class's Class object.
Careless locking can cause a deadlock, where Thread A holds Lock 1 and waits for Lock 2 while Thread B holds Lock 2 and waits for Lock 1 forever. Deadlocks are prevented by always acquiring multiple locks in a consistent global order.
4.2 Inter-Thread Communication: wait(), notify(), and notifyAll()
Threads often need to coordinate around shared conditions—such as a producer waiting when a buffer is full and a consumer waiting when it is empty. Java provides wait(), notify(), and notifyAll() on java.lang.Object, which must always be called from inside a synchronized context. Calling wait() atomically releases the monitor lock and suspends the thread until another thread calls notify() or notifyAll() on the same monitor object.
class SharedBuffer {
private int data;
private boolean hasValue = false;
public synchronized void produce(int value) throws InterruptedException {
while (hasValue) {
wait(); // Releases lock until consumer reads
}
data = value;
hasValue = true;
System.out.println("Produced: " + value);
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while (!hasValue) {
wait(); // Releases lock until producer writes
}
hasValue = false;
System.out.println("Consumed: " + data);
notifyAll();
return data;
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) throws InterruptedException {
SharedBuffer buf = new SharedBuffer();
Thread producer = new Thread(() -> {
try { for (int i = 1; i <= 3; i++) buf.produce(i * 10); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
try { for (int i = 1; i <= 3; i++) buf.consume(); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.setPriority(Thread.NORM_PRIORITY);
producer.start(); consumer.start();
producer.join(); consumer.join();
}
}Chapter 5: Package Visibility Engineering and Custom Exceptions
5.1 Package Access Visibility Matrix
Java's package system works in tandem with access modifiers to enforce encapsulation across module boundaries. While private limits visibility strictly to the declaring class and public opens access globally, the protected and default (package-private) levels govern cross-package inheritance and intra-package collaboration. Understanding the exact four-tier visibility matrix prevents accidental exposure of internal helper classes and ensures clean API boundaries.
| Access Context | private |
Default (No Modifier) | protected |
public |
|---|---|---|---|---|
| Same Class | Accessible | Accessible | Accessible | Accessible |
| Same Package (Non-Subclass) | Not Accessible | Accessible | Accessible | Accessible |
| Same Package (Subclass) | Not Accessible | Accessible | Accessible | Accessible |
| Different Package (Subclass) | Not Accessible | Not Accessible | Accessible (via inheritance) | Accessible |
| Different Package (Non-Subclass) | Not Accessible | Not Accessible | Not Accessible | Accessible |
Top-level classes themselves may only be declared public or package-private. Declaring internal utility classes without the public keyword hides them from external packages, allowing library authors to refactor internal algorithms without breaking external client code.
5.2 Checked vs. Unchecked Exceptions and Try-With-Resources
Every exception and error in Java inherits from java.lang.Throwable, which splits into two primary branches: Error (severe JVM-level failures such as OutOfMemoryError or StackOverflowError that applications should not attempt to catch) and Exception (recoverable application conditions). Within Exception, subclasses of RuntimeException are unchecked—the compiler does not force callers to catch or declare them—whereas all other Exception subclasses are checked and must either be handled in a try-catch block or declared in the method header with throws.
| Criterion | Checked Exceptions | Unchecked Exceptions | JVM Errors |
|---|---|---|---|
| Base Class | java.lang.Exception (excluding RuntimeException) |
java.lang.RuntimeException |
java.lang.Error |
| Compile-Time Check | Enforced by javac (must catch or declare). |
Not checked at compile time. | Not checked at compile time. |
| Typical Cause | External I/O, missing files, database failures. | Programming bugs (null dereference, bad index). | JVM heap exhaustion, linkage failure. |
| Common Examples | IOException, SQLException, ClassNotFoundException |
NullPointerException, ArithmeticException |
OutOfMemoryError, StackOverflowError |
Modern Java also simplifies deterministic resource cleanup through the try-with-resources statement. Any object implementing java.lang.AutoCloseable declared inside the try (...) header is automatically closed in reverse declaration order when the block exits, even if an exception is thrown inside the body.
5.3 Designing Custom Domain Exceptions
When standard JDK exceptions fail to express domain-specific failures clearly, developers define custom exception classes by extending Exception (for checked business rules) or RuntimeException (for unchecked validation errors). Providing constructors that accept a descriptive message and an optional root cause (Throwable) enables clean exception chaining across architectural layers.
class InsufficientBalanceException extends Exception {
private final double shortfall;
public InsufficientBalanceException(String message, double shortfall) {
super(message);
this.shortfall = shortfall;
}
public double getShortfall() {
return shortfall;
}
}
class SavingsAccount {
private final String accountId;
private double balance;
public SavingsAccount(String accountId, double initialBalance) {
this.accountId = accountId;
this.balance = initialBalance;
}
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive.");
}
if (amount > balance) {
throw new InsufficientBalanceException(
"Withdrawal denied for " + accountId, amount - balance
);
}
balance -= amount;
System.out.println("Withdrawn " + amount + "; Remaining balance: " + balance);
}
}
public class BankExceptionDemo {
public static void main(String[] args) {
SavingsAccount acc = new SavingsAccount("KU-5021", 5000.0);
try {
acc.withdraw(2000.0);
acc.withdraw(4500.0);
} catch (InsufficientBalanceException ex) {
System.err.println(ex.getMessage() + " | Shortfall: " + ex.getShortfall());
} finally {
System.out.println("Transaction audit log finalized.");
}
}
}Chapter 6: Concurrency Patterns, Thread States, and Deadlock Avoidance
6.1 Thread State Machine and Scheduling
A Java thread transitions through six formal states defined in java.lang.Thread.State. When instantiated with new Thread(), it resides in NEW. Calling start() registers the thread with the OS scheduler and moves it to RUNNABLE, where it alternates between waiting for a CPU core and executing instructions. Contending for a synchronized monitor lock places a thread in BLOCKED; calling Object.wait() or Thread.join() without a timeout moves it to WAITING; calling Thread.sleep(ms) places it in TIMED_WAITING; and completing run() transitions it permanently to TERMINATED.
| Thread Creation Approach | Class Hierarchy Impact | Resource Sharing | Recommended Use Case |
|---|---|---|---|
Extending Thread |
Consumes the single allowed superclass slot. | Each thread is a separate object instance. | Simple standalone thread specialization. |
Implementing Runnable |
Class remains free to extend another base class. | Multiple threads can share one Runnable target. |
Production applications and thread pools. |
6.2 Synchronization, Race Conditions, and Deadlock Prevention
A race condition arises when two or more threads read and modify shared mutable state concurrently without mutual exclusion, causing lost updates or corrupted invariants. For example, a compound operation such as count++ compiles into three distinct bytecode steps—read, increment, and write—which can interleave unpredictably across threads. Applying the synchronized keyword to a method or critical code block acquires the intrinsic monitor lock on the target object, guaranteeing that only one thread executes the protected region at a time.
While synchronization prevents race conditions, improper lock ordering can introduce deadlock, a permanent stall where Thread A holds Lock 1 and waits for Lock 2 while Thread B holds Lock 2 and waits for Lock 1. Deadlock requires four simultaneous Coffman conditions: mutual exclusion, hold-and-wait, no preemption, and circular wait. In Java, the cleanest prevention technique is enforcing a strict global lock-acquisition order across all threads.
class TicketInventory {
private int availableSeats;
public TicketInventory(int seats) {
this.availableSeats = seats;
}
public synchronized boolean bookSeat(String passengerName, int requested) {
if (availableSeats >= requested) {
System.out.println(passengerName + " booking " + requested + " seat(s)...");
try { Thread.sleep(50); } catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
availableSeats -= requested;
System.out.println("Confirmed for " + passengerName + ". Left: " + availableSeats);
return true;
}
System.out.println("Sold out for " + passengerName + ". Left: " + availableSeats);
return false;
}
}
public class TicketCounterSync {
public static void main(String[] args) throws InterruptedException {
TicketInventory inventory = new TicketInventory(3);
Runnable task1 = () -> inventory.bookSeat("Arjun", 2);
Runnable task2 = () -> inventory.bookSeat("Meera", 2);
Thread t1 = new Thread(task1, "Counter-1");
Thread t2 = new Thread(task2, "Counter-2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}Module IV: Applets, Graphics and AWT Event Handling
Chapter 1: Java Applets and HTML Integration
1.1 Introduction to Applets and Comparison with Applications
A Java Applet is a small, client-side Java program derived from java.applet.Applet (or javax.swing.JApplet) designed to be embedded in an HTML document and executed inside an applet container such as a legacy web browser or the JDK appletviewer utility. Unlike standalone applications, applets do not define a main() method and execute inside a strict security sandbox that prevents reading/writing local files, running external OS commands, or opening network sockets to hosts other than the originating server.
| Dimension | Java Standalone Application | Java Applet |
|---|---|---|
| Entry Point | Begins execution at public static void main(String[] args). |
No main(); controlled by lifecycle methods (init, start, etc.). |
| Execution Environment | Runs directly via local java command / JVM. |
Embedded in HTML and run inside appletviewer or browser plugin. |
| Security Model | Full access to local filesystem and OS resources (subject to OS permissions). | Restricted sandbox; cannot read/write arbitrary local files. |
| UI Container | Creates its own top-level Frame or JFrame. |
Inherits from Panel via Applet and renders inside page region. |
1.2 Applet Life Cycle
Every applet is governed by five lifecycle methods invoked automatically by the container:
public void init(): Called once when the applet is first loaded. Used to initialize variables, create GUI components, load fonts/colors, and read HTML parameters.public void start(): Called immediately afterinit()and every time the user returns to the page containing the applet. Used to start animations or background threads.public void paint(Graphics g): Called whenever the applet surface needs rendering or repainting (after initialization, window resizing, or callingrepaint()). Receives aGraphicscontext for drawing text and shapes. Internally, callingrepaint()schedulesupdate(Graphics g), which clears the background and invokespaint(g).public void stop(): Called when the user navigates away from the page or minimizes the window, pausing active animations or threads.public void destroy(): Called once just before the applet is unloaded from memory, releasing allocated resources cleanly.
1.3 Creating, Executing, and Embedding Applets in HTML
To create and run an applet, the programmer writes a public class extending Applet, compiles it with javac MyApplet.java, and embeds an <APPLET> tag inside an HTML file (or comment block for appletviewer). Key attributes of the <APPLET> tag are summarized below:
| HTML Attribute / Tag | Purpose and Example |
|---|---|
CODE |
Specifies the compiled .class filename (e.g., CODE="GreetingApplet.class"). |
WIDTH and HEIGHT |
Defines the applet's rectangular display area in pixels. |
CODEBASE |
Optional base URL/folder if the .class file is in a different directory. |
ALT |
Fallback text displayed if the browser cannot run Java applets. |
ALIGN |
Aligns the applet display relative to surrounding text (LEFT, RIGHT, TOP, BOTTOM, MIDDLE). |
HSPACE and VSPACE |
Sets horizontal and vertical pixel margins around the applet box. |
<PARAM NAME="..." VALUE="..."> |
Passes named string parameters into the applet, read via getParameter("name"). |
import java.applet.Applet;
import java.awt.Graphics;
/* <applet code="GreetingApplet.class" width="380" height="150" align="middle" hspace="10" vspace="10">
<param name="student" value="Ananya" />
<param name="course" value="BCA Java Programming" />
</applet> */
public class GreetingApplet extends Applet {
private String studentName;
private String courseTitle;
@Override
public void init() {
studentName = getParameter("student");
courseTitle = getParameter("course");
if (studentName == null) studentName = "Student";
if (courseTitle == null) courseTitle = "Java";
}
@Override
public void paint(Graphics g) {
g.drawString("Welcome, " + studentName, 30, 50);
g.drawString("Course: " + courseTitle, 30, 80);
}
}Chapter 2: The Graphics Class and 2D Geometric Primitives
2.1 Coordinate System, Colors, and Fonts
The java.awt.Graphics class serves as the abstract drawing canvas for applets and AWT components. Its coordinate system places the origin (0, 0) at the top-left corner of the component, with x increasing rightward and y increasing downward in pixels. Before drawing shapes or text, developers configure drawing attributes using g.setColor(Color c) (using constants like Color.BLUE or custom RGB via new Color(r, g, b)) and g.setFont(new Font("SansSerif", Font.BOLD, 16)). The FontMetrics class can also be queried via g.getFontMetrics() to measure exact string pixel widths for centered labels.
2.2 Drawing and Filling Lines, Rectangles, Polygons, Circles, and Arcs
The Graphics class provides paired draw...() (outline) and fill...() (solid interior) methods for standard geometric figures:
| Shape | Outline Method | Filled Method | Key Parameters |
|---|---|---|---|
| Line | drawLine(x1, y1, x2, y2) |
N/A | Start point (x1, y1) and end point (x2, y2). |
| Rectangle | drawRect(x, y, w, h) |
fillRect(x, y, w, h) |
Top-left corner (x, y), width w, height h. |
| Rounded Rectangle | drawRoundRect(x, y, w, h, aw, ah) |
fillRoundRect(x, y, w, h, aw, ah) |
Adds corner arc width aw and arc height ah. |
| Polygon | drawPolygon(xPts, yPts, n) |
fillPolygon(xPts, yPts, n) |
Arrays of X and Y vertices and vertex count n. |
| Circle / Oval | drawOval(x, y, w, h) |
fillOval(x, y, w, h) |
Bounding rectangle; when w == h, draws a circle. |
| Arc | drawArc(x, y, w, h, start, arc) |
fillArc(x, y, w, h, start, arc) |
Bounding box plus start angle and sweep angle in degrees. |
import java.applet.Applet;
import java.awt.*;
public class ShapesCanvasApplet extends Applet {
@Override
public void paint(Graphics g) {
g.setFont(new Font("SansSerif", Font.BOLD, 14));
g.setColor(Color.BLACK);
g.drawString("2D Primitives Showcase", 20, 20);
g.setColor(Color.DARK_GRAY);
g.drawLine(20, 30, 280, 30);
g.setColor(Color.BLUE);
g.drawRect(20, 45, 90, 50);
g.fillRoundRect(130, 45, 90, 50, 15, 15);
g.setColor(Color.RED);
g.drawOval(20, 115, 60, 60); // Circle outline
g.fillArc(100, 115, 80, 80, 0, 135);
int[] xs = {220, 270, 245};
int[] ys = {175, 175, 120};
g.setColor(Color.GREEN);
g.fillPolygon(xs, ys, 3);
}
}Chapter 3: Abstract Window Toolkit (AWT) and Delegation Event Model
3.1 AWT Architecture and Component Hierarchy
The Abstract Window Toolkit (AWT) in java.awt is Java's original platform-dependent GUI framework. AWT components are called heavyweight components because each AWT widget delegates rendering to an underlying native operating system peer (such as a Windows button or X11 window). The root of all visual widgets is Component. A Container is a specialized Component capable of holding other components; its primary subclasses are Panel (an embeddable container without borders or title bar) and Window (which branches into Frame, a top-level window with title bar and borders, and Dialog).
3.2 Event Handlers and Event Listeners (Delegation Event Model)
Modern AWT event processing uses the Delegation Event Model, which separates user interface components from event-handling logic through three participants:
- Event Source: A GUI component (such as a
ButtonorTextField) that generates an event when interacted with and maintains a list of registered listeners viaaddXxxListener(). - Event Object: An instance of a subclass of
java.util.EventObjectencapsulating details about what occurred and which source triggered it (accessible viagetSource()). - Event Listener: An object implementing a listener interface from
java.awt.event. When an event fires, the source invokes the listener's callback method.
| Event Class | Listener Interface | Callback Method(s) & Typical Source |
|---|---|---|
ActionEvent |
ActionListener |
actionPerformed(ActionEvent) — Button click, TextField Enter. |
ItemEvent |
ItemListener |
itemStateChanged(ItemEvent) — Checkbox, Choice, List. |
TextEvent |
TextListener |
textValueChanged(TextEvent) — TextField, TextArea edits. |
MouseEvent |
MouseListener |
mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited. |
KeyEvent |
KeyListener |
keyTyped, keyPressed, keyReleased. |
WindowEvent |
WindowListener |
windowClosing, windowOpened, windowActivated, etc. |
For multi-method listener interfaces like WindowListener (7 methods), MouseListener (5 methods), or KeyListener (3 methods), AWT provides convenience Adapter classes (WindowAdapter, MouseAdapter, KeyAdapter) with empty default implementations so subclasses only override the specific methods they need—commonly via anonymous inner classes.
Chapter 4: AWT Controls and Layout Managers
4.1 Core AWT Controls and Their Event Handling
AWT provides standard interactive controls inside java.awt:
Label: Displays non-editable read-only text with configurable alignment (Label.LEFT,Label.CENTER,Label.RIGHT). Methods:setText(String),getText().TextComponent(TextFieldandTextArea):TextFieldaccepts single-line editable input (and supports echo masking for passwords viasetEchoChar('*')), whileTextAreaprovides multi-line scrollable text editing. Pressing Enter in aTextFieldfires anActionEvent; text edits fire aTextEventhandled byTextListener. Common methods inherited fromTextComponentincludegetText(),setText(),getSelectedText(), andsetEditable(boolean).Button: A push button that fires anActionEventwhen clicked, handled byActionListener.actionPerformed().CheckboxandCheckboxGroup: ACheckboxrepresents an independent boolean toggle firingItemEventto anItemListener. Grouping multiple checkboxes with a sharedCheckboxGroupturns them into mutually exclusive radio buttons.
4.2 Layout Managers
Rather than hardcoding pixel coordinates—which break across screen resolutions and operating systems—AWT containers delegate component sizing and positioning to a LayoutManager:
| Layout Manager | Arrangement Strategy | Default Container / Typical Usage |
|---|---|---|
FlowLayout |
Places components left-to-right in rows, wrapping to the next line when full. | Default for Panel and Applet; toolbars and simple rows. |
BorderLayout |
Divides container into five regions: NORTH, SOUTH, EAST, WEST, CENTER. |
Default for Frame and Window; application shells. |
GridLayout |
Arranges components in an equal-sized rectangular grid of rows and columns. | Calculators, keypads, uniform form grids. |
CardLayout |
Stacks components like deck cards so only one panel is visible at a time. | Multi-step wizards and tabbed views. |
GridBagLayout |
Flexible grid where cells can span multiple rows/columns with weights. | Complex data-entry forms requiring custom alignment. |
import java.awt.*;
import java.awt.event.*;
public class AwtRegistrationFrame extends Frame implements ActionListener, ItemListener, TextListener {
private TextField nameField;
private TextArea bioArea;
private Checkbox maleBox, femaleBox;
private CheckboxGroup genderGroup;
private Button submitBtn;
private Label statusLabel;
public AwtRegistrationFrame() {
super("AWT Event Demo");
setLayout(new BorderLayout(8, 8));
Panel form = new Panel(new GridLayout(4, 2, 6, 6));
form.add(new Label("Student Name:"));
nameField = new TextField(18);
nameField.addTextListener(this);
form.add(nameField);
form.add(new Label("Gender:"));
Panel gPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
genderGroup = new CheckboxGroup();
maleBox = new Checkbox("Male", genderGroup, true);
femaleBox = new Checkbox("Female", genderGroup, false);
maleBox.addItemListener(this);
femaleBox.addItemListener(this);
gPanel.add(maleBox);
gPanel.add(femaleBox);
form.add(gPanel);
form.add(new Label("Notes:"));
bioArea = new TextArea(3, 18);
form.add(bioArea);
submitBtn = new Button("Register");
submitBtn.addActionListener(this);
form.add(submitBtn);
statusLabel = new Label("Waiting for input...");
add(form, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) { dispose(); System.exit(0); }
});
setSize(420, 240);
setVisible(true);
}
@Override
public void textValueChanged(TextEvent e) {
statusLabel.setText("Typing: " + nameField.getText());
}
@Override
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Selected: " + genderGroup.getSelectedCheckbox().getLabel());
}
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText().trim();
statusLabel.setText(name.isEmpty() ? "Enter name!" : "Registered: " + name);
}
public static void main(String[] args) { new AwtRegistrationFrame(); }
}Chapter 5: Parameterized Applets and 2D Graphics Primitives
5.1 Applet vs. Standalone Application and HTML Tag Reference
Although both applets and standalone applications are written in Java and compiled to .class bytecode, their execution environments, entry points, and security boundaries differ substantially. Standalone applications begin at public static void main(String[] args) with unrestricted access to the local filesystem and network, whereas applets extend java.applet.Applet, execute inside a browser or appletviewer sandbox, and follow browser-driven lifecycle callbacks (init, start, paint, stop, destroy).
HTML <APPLET> Attribute |
Required? | Purpose and Behavior |
|---|---|---|
CODE |
Yes | Specifies the compiled .class file name of the Applet subclass. |
WIDTH and HEIGHT |
Yes | Defines the initial pixel dimensions of the applet viewport inside the HTML page. |
CODEBASE |
No | Specifies the base directory or URL where the applet class files reside. |
ALT |
No | Fallback text displayed if the browser recognizes the tag but cannot run Java. |
ALIGN |
No | Controls alignment relative to surrounding HTML text (LEFT, RIGHT, TOP, MIDDLE). |
HSPACE and VSPACE |
No | Sets horizontal and vertical pixel margins around the applet bounding box. |
<PARAM NAME="..." VALUE="..."> |
No | Nested tag passing string key-value configuration read via getParameter(name). |
5.2 Graphics Class Coordinate Geometry and Drawing Methods
The java.awt.Graphics class renders 2D shapes, colors, and text onto an applet or AWT canvas using a Cartesian pixel grid whose origin (0, 0) sits at the top-left corner, with x increasing rightward and y increasing downward. Angles in drawArc and fillArc are measured in degrees counter-clockwise starting from the 3 o'clock horizontal axis.
| Method Signature | Geometric Behavior |
|---|---|
drawLine(int x1, int y1, int x2, int y2) |
Draws a single straight line segment between (x1, y1) and (x2, y2). |
drawRect(int x, int y, int w, int h) |
Draws the outline of a rectangle with top-left corner (x, y), width w, height h. |
fillRect(int x, int y, int w, int h) |
Fills a solid rectangle using the current foreground color. |
drawRoundRect(x, y, w, h, arcW, arcH) |
Draws a rectangle with rounded corners defined by horizontal and vertical arc diameters. |
drawOval(int x, int y, int w, int h) |
Draws an ellipse inscribed inside the bounding rectangle (a circle when w == h). |
fillArc(x, y, w, h, startAngle, arcAngle) |
Fills a pie-slice sector sweeping arcAngle degrees from startAngle. |
drawPolygon(int[] xPts, int[] yPts, int n) |
Connects n coordinate vertices in sequence and closes the polygon automatically. |
setColor(Color c) / setFont(Font f) |
Updates the active drawing color and typography used by subsequent draw calls. |
import java.applet.Applet;
import java.awt.*;
/* <applet code="BarChartApplet.class" width="420" height="280">
<param name="title" value="BCA Semester Marks">
<param name="java" value="88">
<param name="dbms" value="82">
<param name="os" value="76">
</applet> */
public class BarChartApplet extends Applet {
private String chartTitle;
private int[] scores = new int[3];
private final String[] subjects = {"Java", "DBMS", "OS"};
@Override
public void init() {
setBackground(Color.WHITE);
chartTitle = getParameter("title");
if (chartTitle == null) chartTitle = "Score Summary";
scores[0] = parseScore(getParameter("java"), 80);
scores[1] = parseScore(getParameter("dbms"), 75);
scores[2] = parseScore(getParameter("os"), 70);
}
private int parseScore(String val, int fallback) {
try { return val != null ? Integer.parseInt(val) : fallback; }
catch (NumberFormatException e) { return fallback; }
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("SansSerif", Font.BOLD, 14));
g.drawString(chartTitle, 120, 30);
g.drawLine(60, 220, 360, 220);
g.drawLine(60, 50, 60, 220);
for (int i = 0; i < scores.length; i++) {
int barHeight = scores[i] * 150 / 100;
int x = 95 + i * 85;
int y = 220 - barHeight;
g.setColor(new Color(31, 58, 95));
g.fillRect(x, y, 45, barHeight);
g.setColor(Color.BLACK);
g.drawString(subjects[i] + " (" + scores[i] + ")", x - 5, 240);
}
}
}Chapter 6: AWT Event Listeners, Adapter Classes, and Layout Managers
6.1 Delegation Event Model Listeners and Adapter Classes
In Java's Delegation Event Model, a user interaction on an AWT widget (the Event Source) constructs an immutable Event Object and dispatches it to every registered Event Listener. Because interfaces such as MouseListener and WindowListener declare multiple abstract methods, implementing them directly forces a class to write empty stubs for unused events. Java provides abstract Adapter classes (such as MouseAdapter and WindowAdapter) with empty default implementations so subclasses only override the specific callbacks they need.
| Listener Interface | Event Class | Key Callback Methods | Adapter Class |
|---|---|---|---|
ActionListener |
ActionEvent |
actionPerformed(ActionEvent) |
None (single method) |
ItemListener |
ItemEvent |
itemStateChanged(ItemEvent) |
None (single method) |
TextListener |
TextEvent |
textValueChanged(TextEvent) |
None (single method) |
MouseListener |
MouseEvent |
mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited |
MouseAdapter |
KeyListener |
KeyEvent |
keyTyped, keyPressed, keyReleased |
KeyAdapter |
WindowListener |
WindowEvent |
windowClosing, windowOpened, windowClosed, windowActivated, etc. |
WindowAdapter |
6.2 AWT Layout Managers Comparison
Hardcoding pixel coordinates breaks interfaces across operating systems with different font metrics and DPI scaling. AWT delegates component sizing and positioning to LayoutManager implementations attached to each Container via setLayout(...).
| Layout Manager | Default Container | Arrangement Strategy |
|---|---|---|
FlowLayout |
Panel, Applet |
Places components left-to-right at preferred sizes, wrapping onto new rows. |
BorderLayout |
Frame, Window |
Divides container into NORTH, SOUTH, EAST, WEST, and CENTER. |
GridLayout |
Explicitly set | Forces all components into equal-width, equal-height rectangular cells. |
CardLayout |
Explicitly set | Stacks panels like playing cards, displaying one active panel at a time. |
GridBagLayout |
Explicitly set | Aligns varied-size components across weighted grid cells via GridBagConstraints. |
import java.awt.*;
import java.awt.event.*;
public class StudentFeedbackAWT extends Frame implements ActionListener, ItemListener {
private final TextField nameField = new TextField(20);
private final CheckboxGroup modeGroup = new CheckboxGroup();
private final Checkbox onlineCb = new Checkbox("Online", modeGroup, true);
private final Checkbox offlineCb = new Checkbox("Offline", modeGroup, false);
private final TextArea remarksArea = new TextArea(3, 25);
private final Label outputLabel = new Label("Fill form and click Submit.");
public StudentFeedbackAWT() {
super("BCA Course Feedback (AWT)");
setLayout(new BorderLayout(10, 10));
Panel formPanel = new Panel(new GridLayout(4, 2, 6, 6));
formPanel.add(new Label("Student Name:"));
formPanel.add(nameField);
formPanel.add(new Label("Class Mode:"));
Panel radioPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
radioPanel.add(onlineCb);
radioPanel.add(offlineCb);
formPanel.add(radioPanel);
formPanel.add(new Label("Remarks:"));
formPanel.add(remarksArea);
Button submitBtn = new Button("Submit Feedback");
submitBtn.addActionListener(this);
onlineCb.addItemListener(this);
offlineCb.addItemListener(this);
add(formPanel, BorderLayout.CENTER);
add(submitBtn, BorderLayout.EAST);
add(outputLabel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
setSize(480, 220);
setVisible(true);
}
@Override
public void itemStateChanged(ItemEvent e) {
Checkbox selected = modeGroup.getSelectedCheckbox();
outputLabel.setText("Selected mode: " + selected.getLabel());
}
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText().trim();
String mode = modeGroup.getSelectedCheckbox().getLabel();
outputLabel.setText("Saved: " + (name.isEmpty() ? "Anonymous" : name) + " [" + mode + "]");
}
public static void main(String[] args) {
new StudentFeedbackAWT();
}
}Module V: Swing Controls and Java Database Connectivity (JDBC)
Chapter 1: Swing Architecture and Core Swing Controls
1.1 From AWT to Swing: Lightweight Components and MVC
Swing (located in javax.swing) is an advanced GUI toolkit built on top of AWT that addresses AWT's platform inconsistencies and limited widget set. Unlike AWT's heavyweight components that depend on native OS peers, Swing components (prefixed with J, such as JButton and JLabel) are lightweight: they are rendered entirely in pure Java code on top-level heavyweight containers such as JFrame, JDialog, or JApplet. This design guarantees consistent appearance across Windows, Linux, and macOS, supports a Pluggable Look and Feel (Metal, Nimbus, System), and follows a separable Model-View-Controller (MVC) architecture where data models (e.g., ButtonModel, Document) are decoupled from visual rendering.
Every top-level Swing container like JFrame manages a JRootPane containing four layers: the glass pane, layered pane, optional menu bar, and the content pane where application widgets are placed (in modern Java, frame.add(...) delegates directly to the content pane).
| Feature | AWT (java.awt) |
Swing (javax.swing) |
|---|---|---|
| Component Weight | Heavyweight (backed by native OS peers). | Lightweight (drawn in pure Java; only top-level containers are heavyweight). |
| Platform Consistency | Appearance and behavior vary slightly across operating systems. | Uniform cross-platform look with Pluggable Look and Feel. |
| Architecture | Direct peer coupling without formal MVC separation. | Clean MVC-inspired separation between data model and UI delegate. |
| Component Richness | Basic widgets only (no tables, trees, or icons on buttons). | Rich components including icons, tooltips, borders, tables, and scroll panes. |
1.2 Core Swing Controls: JLabel, JTextField, JTextArea, JButton, and JRadioButton
Developing desktop forms in Swing relies on five foundational controls housed inside containers like JFrame and JPanel:
| Swing Control | Key Constructors | Essential Methods & Events |
|---|---|---|
JLabel |
JLabel(String text), JLabel(String, int align), JLabel(Icon) |
setText(), getText(), setIcon(); display-only (no action events). |
JTextField |
JTextField(int cols), JTextField(String, int cols) |
getText(), setText(), setEditable(); fires ActionEvent on Enter. |
JTextArea |
JTextArea(int rows, int cols) |
append(), setLineWrap(true), setWrapStyleWord(true); wrap in JScrollPane. |
JButton |
JButton(String text), JButton(String, Icon) |
setMnemonic(), setToolTipText(); fires ActionEvent on click. |
JRadioButton |
JRadioButton(String text, boolean selected) |
isSelected(), setSelected(); group with ButtonGroup; fires ActionEvent/ItemEvent. |
A common pitfall with JRadioButton is forgetting ButtonGroup: adding radio buttons to a JPanel lays them out visually, while adding the same buttons to a ButtonGroup enforces logical mutual exclusion so selecting one automatically deselects the others.
Chapter 2: Swing Event Handling and Thread-Safe UI Updates
2.1 Event Dispatch Thread and Swing Form Integration
Swing components are not thread-safe; all creation and mutation of Swing widgets should execute on the Event Dispatch Thread (EDT) by wrapping startup in SwingUtilities.invokeLater(...). Setting frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) eliminates the boilerplate WindowAdapter needed in AWT. Validation feedback can be shown either in a status JLabel or in modal popups via JOptionPane.showMessageDialog(...).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StudentFeedbackForm extends JFrame implements ActionListener {
private JTextField nameField;
private JRadioButton bcaBtn, bscBtn;
private JTextArea remarksArea;
private JLabel resultLabel;
public StudentFeedbackForm() {
super("Swing Feedback Form");
setLayout(new BorderLayout(10, 10));
JPanel formPanel = new JPanel(new GridLayout(3, 2, 8, 8));
formPanel.add(new JLabel("Student Name:"));
nameField = new JTextField(18);
formPanel.add(nameField);
formPanel.add(new JLabel("Programme:"));
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
bcaBtn = new JRadioButton("BCA", true);
bscBtn = new JRadioButton("BSc CS");
ButtonGroup progGroup = new ButtonGroup();
progGroup.add(bcaBtn);
progGroup.add(bscBtn);
radioPanel.add(bcaBtn);
radioPanel.add(bscBtn);
formPanel.add(radioPanel);
formPanel.add(new JLabel("Remarks:"));
remarksArea = new JTextArea(4, 18);
remarksArea.setLineWrap(true);
remarksArea.setWrapStyleWord(true);
formPanel.add(new JScrollPane(remarksArea));
JButton submitBtn = new JButton("Submit Feedback");
submitBtn.setMnemonic('S');
submitBtn.addActionListener(this);
resultLabel = new JLabel("Fill details and click Submit.", SwingConstants.CENTER);
add(formPanel, BorderLayout.CENTER);
add(submitBtn, BorderLayout.EAST);
add(resultLabel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText().trim();
if (name.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter a name.", "Validation", JOptionPane.WARNING_MESSAGE);
return;
}
String prog = bcaBtn.isSelected() ? "BCA" : "BSc CS";
resultLabel.setText("Saved: " + name + " (" + prog + ")");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(StudentFeedbackForm::new);
}
}Chapter 3: Java Database Connectivity (JDBC) and Driver Types
3.1 JDBC Architecture and Core Interfaces
Java Database Connectivity (JDBC) is a standard Java API (in java.sql and javax.sql) that enables Java applications to interact uniformly with relational databases such as MySQL, PostgreSQL, and Oracle. JDBC decouples application code from vendor-specific wire protocols: the programmer codes against standard JDBC interfaces, while a vendor-supplied JDBC Driver translates calls into database commands. JDBC supports both two-tier architecture (Java client talks directly to database server via driver) and three-tier architecture (Java client sends requests to a middle-tier application server, which executes JDBC calls against the database).
Core JDBC classes and interfaces include:
DriverManager: Manages registered JDBC drivers and opens database connections viagetConnection(url, user, password).Connection: Represents an active session with a database; creates statements and manages transactions (setAutoCommit(false),commit(),rollback()).Statement,PreparedStatement, andCallableStatement: Execute static SQL, precompiled parameterized SQL (preventing SQL injection), and database stored procedures respectively.ResultSet: Holds tabular rows returned by aSELECTquery with a cursor navigated vianext()and typed getters such asgetInt("id")andgetString("name").SQLException: Checked exception conveying database error codes, SQLState, and diagnostic messages.
3.2 The Four Types of JDBC Drivers
JDBC defines four architectural driver categories based on how they translate JDBC calls to the target database:
| Driver Type | Name | Mechanism | Pros and Cons |
|---|---|---|---|
| Type 1 | JDBC-ODBC Bridge Driver | Translates JDBC calls into ODBC calls, which invoke native DB drivers. | Easy prototyping, but slow due to two translation layers; removed in Java 8+. |
| Type 2 | Native-API / Partly Java Driver | Converts JDBC calls into vendor-specific C/C++ client library calls. | Faster than Type 1, but requires native client binaries on every client machine. |
| Type 3 | Network Protocol / Pure Java Driver | Sends platform-neutral calls over network to middleware server, which talks to DB. | 100% pure Java, supports multiple DBs via middleware, adds extra server tier. |
| Type 4 | Thin / Native-Protocol Pure Java Driver | Converts JDBC calls directly into the database's native TCP/IP network protocol. | Fastest, 100% pure Java, zero native libs; industry standard (e.g., MySQL Connector/J). |
3.3 Statement vs. PreparedStatement vs. CallableStatement
| Interface | Compilation & Performance | SQL Injection Safety | Primary Use Case |
|---|---|---|---|
Statement |
Parsed and compiled on every execution. | Vulnerable if user input is concatenated into SQL strings. | One-off static DDL statements (CREATE TABLE). |
PreparedStatement |
Precompiled once by DB; fast for repeated parameterized calls. | Safe: ? placeholders bind parameters as typed values, not SQL syntax. |
All parameterized INSERT, UPDATE, DELETE, SELECT queries. |
CallableStatement |
Invokes precompiled stored procedures inside the database. | Safe via bound IN, OUT, and INOUT parameters. |
Complex server-side database routines. |
Chapter 4: JDBC Connectivity with MySQL
4.1 Seven Standard Steps for MySQL Connectivity
Connecting a Java program to a MySQL database using the Type 4 MySQL Connector/J driver (mysql-connector-j.jar on classpath) follows seven systematic steps:
- Import JDBC package:
import java.sql.*; - Load/Register the Driver: Modern JDBC 4.0+ drivers auto-register via ServiceLoader, or can be loaded explicitly with
Class.forName("com.mysql.cj.jdbc.Driver");. - Establish Connection: Call
DriverManager.getConnection("jdbc:mysql://localhost:3306/college_db", "root", "secret"). - Create Statement / PreparedStatement: Obtain
PreparedStatement ps = con.prepareStatement("INSERT INTO students(id, name) VALUES (?, ?)");. - Execute SQL Query or Update: Use
executeQuery()forSELECT(returnsResultSet) andexecuteUpdate()forINSERT/UPDATE/DELETE(returns affected row count). - Process the
ResultSet: Loop withwhile (rs.next())and extract column values by name or index. - Close Resources: Close
ResultSet,Statement, andConnection(automatically handled bytry-with-resources).
import java.sql.*;
public class MySqlStudentDao {
private static final String URL = "jdbc:mysql://localhost:3306/college_db";
private static final String USER = "root";
private static final String PASS = "password";
public static void main(String[] args) {
String insertSql = "INSERT INTO students (roll_no, name, sem) VALUES (?, ?, ?)";
String updateSql = "UPDATE students SET sem = ? WHERE roll_no = ?";
String selectSql = "SELECT roll_no, name, sem FROM students ORDER BY roll_no";
try (Connection con = DriverManager.getConnection(URL, USER, PASS)) {
// 1. Parameterized INSERT
try (PreparedStatement ps = con.prepareStatement(insertSql)) {
ps.setInt(1, 501);
ps.setString(2, "Rahul Menon");
ps.setInt(3, 5);
System.out.println("Inserted rows: " + ps.executeUpdate());
}
// 2. Parameterized UPDATE
try (PreparedStatement psUpd = con.prepareStatement(updateSql)) {
psUpd.setInt(1, 6);
psUpd.setInt(2, 501);
System.out.println("Updated rows: " + psUpd.executeUpdate());
}
// 3. SELECT and iterate ResultSet
try (Statement st = con.createStatement();
ResultSet rs = st.executeQuery(selectSql)) {
while (rs.next()) {
System.out.println(
rs.getInt("roll_no") + " | " +
rs.getString("name") + " | Sem " +
rs.getInt("sem")
);
}
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}4.2 Integrating Swing Forms with MySQL JDBC
In desktop Java applications, Swing UI controls collect user input and invoke JDBC Data Access Object (DAO) methods on button clicks. By keeping SQL logic inside dedicated DAO methods that use PreparedStatement and try-with-resources, the GUI layer remains clean, responsive, and protected against SQL injection and connection leaks.
Chapter 5: Swing Component Architecture and Core Controls
5.1 AWT vs. Swing Architectural Comparison
While AWT delegates rendering to native operating system widgets (making them heavyweight and visually inconsistent across platforms), Swing (javax.swing) renders lightweight components entirely in Java using Java 2D graphics. Swing follows a modified Model-View-Controller (MVC) architecture where each widget separates its data model (for example, Document for text components or ButtonModel for buttons) from its pluggable UI delegate. Furthermore, Swing components support automatic double buffering to eliminate screen flicker and require all UI creation and updates to execute on the Event Dispatch Thread (EDT) via SwingUtilities.invokeLater.
| Comparison Criterion | AWT (java.awt) |
Swing (javax.swing) |
|---|---|---|
| Component Weight | Heavyweight (backed by native OS peers). | Lightweight (drawn purely in Java bytecode). |
| Look and Feel | Platform-dependent (varies across Windows/Linux/macOS). | Pluggable Look-and-Feel (Metal, Nimbus, System). |
| Architecture | Direct peer-coupled component model. | Modified MVC (separates data model from UI delegate). |
| Component Richness | Basic widgets only (Button, Label, TextField). |
Rich widgets (JTable, JTree, JTabbedPane, icons, tooltips). |
| Double Buffering | Manual off-screen image buffering required. | Built-in automatic double buffering by default. |
5.2 Core Swing Controls Reference
The syllabus focuses on five essential interactive Swing controls hosted inside JFrame and JPanel containers: JLabel, JTextField, JTextArea, JButton, and JRadioButton.
| Swing Class | Primary Role | Key Methods and Patterns |
|---|---|---|
JFrame |
Top-level application window with title bar and close button. | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), setSize(w, h), pack(). |
JLabel |
Displays non-editable text, icons, or basic HTML captions. | setText(str), setIcon(icon), setHorizontalAlignment(...). |
JTextField |
Single-line editable text input box. | getText(), setText(str), setEditable(boolean), addActionListener(...). |
JTextArea |
Multi-line plain text editor (typically wrapped in JScrollPane). |
append(str), setLineWrap(true), setWrapStyleWord(true). |
JButton |
Push button triggering command actions on click. | addActionListener(...), setMnemonic(KeyEvent.VK_S), setEnabled(boolean). |
JRadioButton |
Mutually exclusive option button when paired with ButtonGroup. |
group.add(rb), isSelected(), addItemListener(...). |
import javax.swing.*;
import java.awt.*;
public class CourseEnrollmentSwing extends JFrame {
private final JTextField nameField = new JTextField(18);
private final JRadioButton sem5Radio = new JRadioButton("Semester V", true);
private final JRadioButton sem6Radio = new JRadioButton("Semester VI");
private final JTextArea logArea = new JTextArea(6, 28);
public CourseEnrollmentSwing() {
super("University of Kerala — BCA Enrollment");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
ButtonGroup semGroup = new ButtonGroup();
semGroup.add(sem5Radio);
semGroup.add(sem6Radio);
JPanel inputPanel = new JPanel(new GridLayout(3, 2, 6, 6));
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
inputPanel.add(new JLabel("Student Name:"));
inputPanel.add(nameField);
inputPanel.add(new JLabel("Target Semester:"));
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.add(sem5Radio);
radioPanel.add(sem6Radio);
inputPanel.add(radioPanel);
JButton enrollBtn = new JButton("Enroll Student");
inputPanel.add(new JLabel("Action:"));
inputPanel.add(enrollBtn);
logArea.setEditable(false);
logArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(logArea);
enrollBtn.addActionListener(e -> {
String student = nameField.getText().trim();
if (student.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter a student name.");
return;
}
String sem = sem5Radio.isSelected() ? "Semester V" : "Semester VI";
logArea.append("Enrolled: " + student + " -> " + sem + "\n");
nameField.setText("");
});
add(inputPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CourseEnrollmentSwing::new);
}
}Chapter 6: JDBC Driver Architecture and Complete MySQL CRUD
6.1 Comparison of JDBC Driver Types (Type 1 to Type 4)
Java Database Connectivity (java.sql) decouples Java application code from vendor-specific database protocols using the DriverManager and Driver interfaces. Historically, Sun Microsystems categorized JDBC drivers into four architectural types based on how they translate JDBC API calls into native DBMS commands.
| Driver Type | Translation Mechanism | Native Code Required? | Performance & Portability |
|---|---|---|---|
| Type 1: JDBC-ODBC Bridge | Translates JDBC calls to ODBC calls, then to DB via ODBC driver. | Yes (ODBC driver + native bridge). | Slowest; non-portable; removed in Java 8+. |
| Type 2: Native-API Driver | Converts JDBC calls directly to vendor C/C++ client libraries. | Yes (vendor client library on each host). | Faster than Type 1; tied to OS platform binaries. |
| Type 3: Network Protocol | Sends DB-neutral calls over TCP/IP to middleware server. | No on client (pure Java client). | High flexibility; supports multi-DB enterprise routing. |
| Type 4: Thin / Pure Java | Translates JDBC calls directly into DBMS wire protocol. | No (100% pure Java). | Fastest and most portable (e.g., MySQL Connector/J). |
6.2 Statement vs. PreparedStatement and Transaction Management
Executing SQL through JDBC uses Statement for static parameterless queries, PreparedStatement for precompiled parameterized SQL, and CallableStatement for database stored procedures. Always prefer PreparedStatement for user-supplied values because it precompiles the execution plan on the MySQL server and binds parameters safely, eliminating SQL injection vulnerabilities. For multi-step operations such as fee transfers, disabling auto-commit via conn.setAutoCommit(false) allows atomic conn.commit() or conn.rollback() control.
| Interface | Compilation | SQL Injection Safety | Primary Use Case |
|---|---|---|---|
Statement |
Parsed and compiled on every execution. | Vulnerable if strings are concatenated. | Static DDL (CREATE TABLE) or parameterless queries. |
PreparedStatement |
Precompiled once and reused with bound ? placeholders. |
Safe (parameters escaped at protocol level). | All parameterized INSERT, SELECT, UPDATE, DELETE. |
CallableStatement |
Invokes precompiled stored procedures inside DBMS. | Safe when using parameterized IN/OUT bindings. | Complex server-side stored routines. |
6.3 Complete MySQL JDBC CRUD Implementation
The following complete program demonstrates all four CRUD (Create, Read, Update, Delete) operations against a MySQL bca_db database using Connector/J (Type 4 driver), parameterized PreparedStatement queries, explicit transaction handling, and try-with-resources cleanup.
import java.sql.*;
public class StudentJdbcCrud {
private static final String URL = "jdbc:mysql://localhost:3306/bca_db?useSSL=false";
private static final String USER = "root";
private static final String PASS = "password";
public static void insertStudent(Connection conn, int id, String name, int sem) throws SQLException {
String sql = "INSERT INTO students (id, name, sem) VALUES (?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, id);
ps.setString(2, name);
ps.setInt(3, sem);
int rows = ps.executeUpdate();
System.out.println("Inserted rows: " + rows);
}
}
public static void listStudents(Connection conn) throws SQLException {
String sql = "SELECT id, name, sem FROM students ORDER BY id";
try (PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.printf("ID=%d | Name=%s | Sem=%d%n",
rs.getInt("id"), rs.getString("name"), rs.getInt("sem"));
}
}
}
public static void updateSemester(Connection conn, int id, int newSem) throws SQLException {
String sql = "UPDATE students SET sem = ? WHERE id = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, newSem);
ps.setInt(2, id);
System.out.println("Updated rows: " + ps.executeUpdate());
}
}
public static void deleteStudent(Connection conn, int id) throws SQLException {
String sql = "DELETE FROM students WHERE id = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, id);
System.out.println("Deleted rows: " + ps.executeUpdate());
}
}
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASS)) {
conn.setAutoCommit(false);
try {
insertStudent(conn, 501, "Karthik Menon", 5);
updateSemester(conn, 501, 6);
listStudents(conn);
deleteStudent(conn, 501);
conn.commit();
} catch (SQLException ex) {
conn.rollback();
System.err.println("Transaction rolled back: " + ex.getMessage());
}
} catch (SQLException e) {
System.err.println("Connection error: " + e.getMessage());
}
}
}University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 5 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Java Programming (University of Kerala BCA Sem 5)
Java Programming (UK5DSCCAP305 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in java programming. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Java Programming Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Java
A programming paradigm represents a fundamental style or methodology of structuring computer programs and reasoning about computation. Over the history of software engineering, programming languages have evolved to manage increasing software complexity, shifting from low-level hardware-centric instructions to high-level abstractions that mirror real-world problem domains. Understanding these paradigms explains why object-oriented programming emerged as the dominant model for large-scale enterprise and desktop systems.
Classes, Objects, Inheritance, Interfaces, Strings and I/O Streams
In Java, a class serves as the fundamental unit of encapsulation, combining state (fields) and behavior (methods) into a reusable blueprint. A class declaration begins with optional modifiers (such as public ), the keyword class, the class identifier, and a body enclosed in braces. Creating an object from a class involves three distinct steps: declaration of a reference variable on the stack ( Student s; ), instantiation using the new operator which allocates memory for instance fields on the heap, and initialization by invoking a constructor ( s = new Student(); ).
Packages, Exception Handling and Multithreading
As software grows into dozens or hundreds of classes, placing all classes in a single default namespace causes naming collisions and poor organization. A package in Java is a namespace mechanism that groups related classes, interfaces, and sub-packages into a hierarchical directory structure. Packages provide three primary benefits: they prevent naming conflicts (for instance, java.util.Date and java.sql.Date coexist cleanly in different packages), they enable controlled access protection via package-private and protected visibility, and they simplify modular distribution in JAR archives.
Applets, Graphics and AWT Event Handling
A Java Applet is a small, client-side Java program derived from java.applet.Applet (or javax.swing.JApplet ) designed to be embedded in an HTML document and executed inside an applet container such as a legacy web browser or the JDK appletviewer utility. Unlike standalone applications, applets do not define a main() method and execute inside a strict security sandbox that prevents reading/writing local files, running external OS commands, or opening network sockets to hosts other than the originating server.
Swing Controls and Java Database Connectivity (JDBC)
Swing (located in javax.swing ) is an advanced GUI toolkit built on top of AWT that addresses AWT's platform inconsistencies and limited widget set. Unlike AWT's heavyweight components that depend on native OS peers, Swing components (prefixed with J, such as JButton and JLabel ) are lightweight: they are rendered entirely in pure Java code on top-level heavyweight containers such as JFrame, JDialog, or JApplet.
Core Curriculum & Key Topics
- Paradigms of Programming Languages and Object-Oriented Concepts
- 1 Evolution of Programming Paradigms
- 2 Basic Concepts of Object-Oriented Programming
- 3 Procedure-Oriented Programming vs. Object-Oriented Programming
- 4 Benefits and Applications of OOP
- Java Fundamentals, JVM, JDK, JRE, and Bytecode
- 1 History and Evolution of Java
- 2 Key Features of Java
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of java programming.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Java Programming
The evaluation framework for Java Programming (UK5DSCCAP305) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK5DSCCAP305 (Java Programming) examination: 1. Write Clean, Traceable Code Snippets: Always include well-indented syntax examples with sample input and expected output for programming questions. 2. Explain Logic & Control Flow Step-by-Step: Before writing full programs, briefly outline the algorithm, key functions, or class hierarchy so examiners can award full step marks. 3. Highlight Edge Cases & Syntax Rules: Mention common runtime pitfalls, data type constraints, or security/validation practices where relevant. 4. Manage Time Across Sections: For the 2.5-hour 70-mark external paper, allocate 25 minutes to Part A definitions, 50 minutes to Part B short programs and comparisons, and 75 minutes to Part C full code-backed essays.
Exam Preparation & Study Guides — Java Programming
What is Programming Paradigms and why is it important in Java Programming?
A programming paradigm defines the fundamental methodology for structuring computation, managing state, and decomposing complex software systems into maintainable modules.
What is Data Security & Decomposition and why is it important in Java Programming?
POP exposes global data openly to all functions and decomposes by procedures, whereas OOP protects internal state via encapsulation and decomposes by interacting objects.
What is Java Runtime Environment (JRE) and why is it important in Java Programming?
Software distribution containing the JVM implementation together with core standard class libraries (
What is Method Overloading and why is it important in Java Programming?
Defining multiple methods within the same class sharing an identical name but differing in number, data type, or sequence of parameters, resolved by the compiler at compile time (compile-time polymorphism).
What is Advantages of Exception Handling and why is it important in Java Programming?
Preserves application stability, propagates error context up the call stack cleanly, isolates error-handling blocks from core algorithms, and enables deterministic resource cleanup.
What is the official course code and credit structure for Java Programming at University of Kerala?
Java Programming carries the official course code UK5DSCCAP305 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Java Programming?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Java Programming (UK5DSCCAP305) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 5 Subjects
Browse study notes for other courses in BCA Sem 5:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.