0% found this document useful (0 votes)
3 views23 pages

ECAP615 Java UnitWise Notes

The document provides comprehensive notes on Programming in Java, covering 14 units that include topics such as arrays, strings, collections, multithreading, and JDBC. Each unit features key concepts explained in simple terms, code examples, and case studies demonstrating real-life applications of Java. It serves as a valuable resource for understanding Java programming fundamentals and practical implementations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views23 pages

ECAP615 Java UnitWise Notes

The document provides comprehensive notes on Programming in Java, covering 14 units that include topics such as arrays, strings, collections, multithreading, and JDBC. Each unit features key concepts explained in simple terms, code examples, and case studies demonstrating real-life applications of Java. It serves as a valuable resource for understanding Java programming fundamentals and practical implementations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications

Harjinder Kaur | Lovely Professional University

ECAP615

Programming in Java
Unit-wise Key Notes · Concept Explanations · Case Studies · Code Examples · Real-Life Applications

14 Units | Arrays · Strings · Collections · Multithreading · Synchronization · Swings · JDBC · Networking

Harjinder Kaur | Lovely Professional University

How to use these notes: Each unit begins with a summary banner listing topics covered. Key concepts are explained in plain
language with real-life analogies, followed by code examples with actual Java syntax, and a case study showing how the concept is
applied in practice. A quick-reference table at the end of each unit summarises all key learnings.

Page 1
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 1

Introduction to Java
What is Java · Platforms · Features · JDK/JVM/JRE · Data Types · Operators · Wrapper Classes · Nested Classes

1.1 What is Java?


Definition: Java is a high-level, robust, object-oriented, platform-independent, and secure programming language developed by
James Gosling at Sun Microsystems in 1995. Originally named "OAK", it was renamed Java. It is both a language and a platform.
Core Philosophy: "Write Once, Run Anywhere (WORA)" — compile source code once into bytecode, which can run on any platform
that has a JVM installed.
OOP Pillars supported: Encapsulation, Inheritance, Polymorphism, Abstraction.

Key Features of Java


Concept / Topic Simple Explanation Real-Life Application Similar / Related

Platform Independent Java code compiles to bytecode Android apps run on all Android Python, Kotlin
(.class file), which runs on any OS phones regardless of manufacturer.
via JVM. Not tied to specific
hardware.

Object Oriented Everything in Java is an object. Modelling a Bank Account as a class C++, Python, Ruby
Classes are blueprints; objects are with deposit(), withdraw() methods.
instances. Supports all 4 OOP
pillars.

Secure No explicit pointers, strong type Java EE powers secure banking and Rust, C# security
checking, bytecode verification, and payment systems like PayPal. model
SecurityManager prevent
unauthorized memory access.

Robust Strong memory management, Enterprise servers running Java handle .NET GC, Python GC
automatic garbage collection, millions of transactions without memory
exception handling prevent crashes leaks.
and memory leaks.

Multithreaded Java has built-in support for A web server handles 1000 client Go routines, Python
concurrent execution of multiple requests simultaneously using threads. threading
threads within one program.

Distributed Java has extensive networking Building REST APIs, microservices, Go, [Link], gRPC
libraries ([Link]) for building and RMI-based distributed systems.
distributed applications over the
internet.

JDK, JVM and JRE — Explained

JVM (Java Virtual Machine): An abstract machine that provides a runtime environment to execute Java bytecode. It handles class
loading, bytecode verification, execution, heap management (objects), stack (local vars), method area, and PC registers. Makes Java
platform-independent.
JRE (Java Runtime Environment): Superset of JVM — contains JVM + class libraries + supporting files needed to run Java
programs. Subset of JDK. No development tools included.
JDK (Java Development Kit): Complete development toolkit — includes JRE + compiler (javac), debugger, monitoring tools, and
API documentation. Used by developers to write, compile, and debug Java programs.
Compilation Flow: Source (.java) → javac compiler → Bytecode (.class) → JVM interprets/executes bytecode → Output.

// First Java Program — Structure

Page 2
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

package myapp; // Package declaration (optional) import [Link].*; // Import statement public class
FirstProgram { // Class declaration public static void main(String args[]) { // Entry point
[Link]("My first Java program"); // Output } } // Compile: javac [Link] → generates
[Link] // Run: java FirstProgram

Data Types in Java

Primitive Types (8): boolean (1 bit), char (16-bit Unicode), byte (8-bit, -128 to 127), short (16-bit), int (32-bit), long (64-bit), float
(32-bit IEEE754), double (64-bit IEEE754).
Non-Primitive Types: String, Arrays, Classes, Interfaces — stored in heap memory, accessed via references.
Default Values: int/long/float/double → 0, boolean → false, char → '\u0000', Object → null.

Wrapper Classes & Autoboxing

Wrapper Classes wrap primitive types into objects so they can be used in Collections (which require objects). Each primitive has a
wrapper: int → Integer, char → Character, boolean → Boolean, double → Double, etc.
Autoboxing: Automatic conversion from primitive → wrapper object: Integer i = 5; (compiler does: Integer i = [Link](5);)
Unboxing: Automatic conversion from wrapper → primitive: int x = i; (compiler does: int x = [Link]();)
Immutability: Wrapper class objects are immutable — once a value is assigned, it cannot be changed.

Nested Classes

Static Nested Class: Declared with static keyword inside an outer class. Does NOT need an instance of the outer class. Cannot
access non-static members of outer class directly.
Inner Class (non-static): Always associated with an outer class object. Can access all members (including private) of the outer
class.
Anonymous Inner Class: A class with no name, created and instantiated in a single expression. Used to override a method of a
class or interface on the fly.
Local Inner Class: Defined inside a method body. Cannot be accessed outside that method.

■ CASE STUDY: Login System using OOP + JDK

A banking app written in Java defines a BankAccount class (encapsulation) with private balance field and public deposit(), withdraw(),
getBalance() methods. The AccountManager inherits BankAccount (inheritance). A SavingsAccount overrides the interest calculation
(polymorphism). The app compiles with javac, runs via JVM, and the same .class bytecode runs on Windows, Linux, and Mac servers
without recompiling. Wrapper classes (Integer, Double) are used when storing account numbers in a HashMap. An anonymous inner
class handles the ActionListener for a login button click in the GUI.

Page 3
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 2

Arrays and Strings


Arrays · 1D/2D/Multi-dim Arrays · String · String Methods · StringBuffer · StringBuilder · Access Specifiers · Inheritance

2.1 Arrays
Definition: An array is a fixed-size, sequential collection of elements of the same data type stored in contiguous memory locations.
Array length is fixed at creation time. Index starts at 0.
Declaration: int[] marks; or int marks[];
Creation: marks = new int[5]; — allocates memory for 5 integers, initialised to 0 by default.
Declaration + Init: int[] marks = {90, 85, 78, 92, 88}; — array literal.
2D Array: int[][] matrix = new int[3][4]; — 3 rows, 4 columns. Access: matrix[row][col].
Multi-dim: int[][][] cube = new int[2][3][4]; — think of it as layers of 2D tables.

// Array Operations

int[] scores = {85, 90, 78, 92, 88}; [Link]([Link]); // 5 [Link](scores[0]); //


85 (first element) // 2D Array — multiplication table int[][] table = new int[3][3]; for(int i=0; i<3; i++)
for(int j=0; j<3; j++) table[i][j] = (i+1) * (j+1);

2.2 Strings
String in Java is an object of class [Link]. Strings are immutable — once created, the value cannot be changed. Every
modification creates a new String object.
String Constant Pool: When you write String s = "hello"; JVM looks in the pool — if "hello" exists, it returns that reference. If not,
creates a new object in the pool. Saves memory.
Using new keyword: String s = new String("hello"); — always creates a new heap object even if the value exists in the pool.
Key Methods: length(), charAt(i), indexOf("sub"), substring(start,end), toLowerCase(), toUpperCase(), trim(), replace(old,new),
equals(), equalsIgnoreCase(), compareTo(), contains(), split(), concat().

// String Methods Demo

String name = "Hello Java"; [Link]([Link]()); // 10 [Link]([Link](6)); // J


[Link]([Link]("Java")); // 6 [Link]([Link](6)); // Java
[Link]([Link]()); // HELLO JAVA [Link]([Link]("Java","World")); //
Hello World [Link]([Link]("Java")); // true [Link]("abc".compareTo("abc")); // 0
(equal)

StringBuffer vs StringBuilder
Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread Safety Yes (immutable) Yes (synchronized) No (not synchronized)

Performance Slow (new object each time) Moderate Fast

When to use Constant text, keys, config Multi-threaded string building Single-thread, high performance

Access Specifiers
private: Accessible only within the same class. Strictest restriction. Used for data encapsulation (hiding fields).
default (package-private): No keyword written. Accessible within the same package only.
protected: Accessible within same package + subclasses (even in different packages).
public: Accessible everywhere — same class, same package, different packages, subclasses.

Inheritance

Page 4
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

Single: One child inherits one parent. class Dog extends Animal {}
Multilevel: Chain — BabyDog extends Dog, Dog extends Animal. BabyDog inherits all.
Hierarchical: Multiple children inherit one parent: Dog extends Animal, Cat extends Animal.
Multiple (via Interfaces): Java does NOT support multiple class inheritance. Achieved via interfaces: class Animal implements
AnimalEat, AnimalTravel {}
extends keyword for class inheritance. implements keyword for interface.
super keyword: Refers to immediate parent class constructor/method.

■ CASE STUDY: E-Commerce Product Catalogue

An online store models its catalogue using OOP: Product is the base class with name, price, category fields. Electronics extends
Product adding warranty. Clothing extends Product adding size, fabric. A String[] productNames array stores 1000 product names; a
2D String[][] grid stores product-vs-attribute data. StringBuffer builds dynamic HTML product description pages (mutable, thread-safe
for concurrent web requests). StringBuilder builds query strings internally (single-thread, fast). Access specifiers ensure price and
discount fields are private — only accessible via getters, preventing malicious code from directly manipulating prices.

Page 5
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 3

Collection Framework
ArrayList · LinkedList · ListIterator · Set · HashSet · TreeSet · Queue · PriorityQueue

3.1 The Java Collection Framework


The Collection Framework ([Link] package) provides a unified architecture of interfaces and classes for storing and manipulating
groups of objects. Unlike arrays, collections are dynamic — they grow and shrink automatically.
Key Interfaces: Collection → List (ordered, allows duplicates), Set (no duplicates), Queue (FIFO), Map (key-value pairs).
Key Classes: ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, HashMap, TreeMap.

ArrayList

ArrayList extends AbstractList and implements List. Backed by a resizable array. Elements accessible by index. Allows null and
duplicate values. Not synchronized (not thread-safe).
Initial capacity: 10 (default). When exceeded, grows by 50% automatically.
Operations: add(obj), add(index,obj), set(index,obj), get(index), remove(index), size(), contains(obj), sort using [Link]().
When to use: Frequent reads/random access. Slower for insertions/deletions in the middle.

// ArrayList Operations

import [Link].*; ArrayList cars = new ArrayList(); [Link]("BMW"); [Link]("Ford"); [Link]("Mazda");


[Link](0, "Opel"); // Update index 0 [Link]([Link](1)); // Ford [Link]("Ford"); // Remove
by value [Link]([Link]()); // 2 [Link](cars); // Sort alphabetically for(String c :
cars) [Link](c); // Enhanced for loop

LinkedList
LinkedList implements both List and Deque. Each element (node) stores data + reference to next (and previous in doubly linked). No
index-based access — must traverse.
Fast at: Insertions/deletions at beginning or end (O(1)). Slow at random access (O(n)).
Key methods: addFirst(), addLast(), removeFirst(), removeLast(), getFirst(), getLast(), peek(), poll(), offer().
ListIterator: Bidirectional iterator — can traverse both forward (next(), nextIndex()) and backward (previous(), previousIndex()).
Supports add(), set(), remove() during iteration.

Set Interface — HashSet and TreeSet


Feature HashSet TreeSet

Duplicates Not allowed Not allowed

Order No guaranteed order (uses hashing) Sorted ascending order (natural/comparator)

Null Allows one null Does NOT allow null (throws NullPointerException)

Performance O(1) add/remove/search O(log n) — uses Red-Black tree

Use when Fast lookup, order not needed Need sorted unique elements

Queue and PriorityQueue


Queue: First-In-First-Out (FIFO) data structure. Elements added at rear, removed from front.
PriorityQueue: Elements processed based on priority (smallest first by default — min-heap). Use Comparator to change priority
order. Operations: offer() to add, poll() to remove (returns null if empty), peek() to view head.
Queue methods: offer() (add without exception), poll() (remove, returns null), peek() (view without removing), add() (add, throws
exception if full), remove() (remove, throws exception if empty).

■ CASE STUDY: Hospital Queue Management System

Page 6
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

A hospital OPD (Out-Patient Department) uses Java Collections: ArrayList stores all registered patients (dynamic size, random
access by ID). A PriorityQueue schedules patients by severity — critical patients (priority 1) are seen before routine cases (priority 5).
HashSet stores unique doctor IDs to prevent duplicates. TreeSet stores specialisations in sorted alphabetical order for the dropdown
menu. LinkedList implements the waiting list where patients can be added to front (emergency) or back (normal).

Page 7
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 4

More on Collection Framework


Comparable Interface · Comparator Interface · Properties Class · Lambda Expressions

4.1 Comparable Interface


Comparable is in [Link] package. Allows objects to define their natural ordering. The class itself implements Comparable and
overrides compareTo(T obj).
compareTo() returns: negative → current < argument, 0 → equal, positive → current > argument.
[Link](list) uses compareTo() automatically when the class implements Comparable.
Limitation: Only one sort sequence. Cannot sort the same class by different fields simultaneously.

4.2 Comparator Interface


Comparator is in [Link] package. Defines custom ordering in a separate class. Overrides compare(T o1, T o2).
Multiple orderings: Create separate Comparator classes for different sort criteria — SortByAge, SortByName, SortByRoll — and
pass to [Link](list, comparator).
Key difference from Comparable: Comparable modifies the class itself (natural order). Comparator is external (custom, multiple
orderings possible without changing the class).

// Comparable vs Comparator

// Comparable — inside class class Student implements Comparable { int roll; String name; int age; public int
compareTo(Student s) { return [Link] - [Link]; } } [Link](list); // sorts by roll (natural order)
// Comparator — external class class SortByAge implements Comparator { public int compare(Student s1, Student
s2) { return [Link] - [Link]; } } [Link](list, new SortByAge()); // sorts by age

4.3 Properties Class


Properties class extends Hashtable. Used to store key-value pairs where both key and value are Strings. Typically used to read
configuration files (.properties).
Key methods: getProperty(key), setProperty(key,value), load(reader), store(writer,comments), propertyNames(),
stringPropertyNames().
System Properties: [Link]() returns all JVM system properties (OS name, Java version, user home, etc.).

4.4 Lambda Expressions


Lambda expressions (Java 8+) provide a concise way to implement functional interfaces (interfaces with a single abstract method).
Syntax: (parameters) -> expression or (params) -> { statements; }
No Lambda: Comparator c = new Comparator() { public int compare(...) { ... } };
With Lambda: Comparator c = (s1, s2) -> [Link] - [Link]; — much shorter!
Used with: [Link](), forEach(), filter(), map(), Runnable, ActionListener.

// Lambda Expression Examples

// Sort with lambda [Link](list, (s1,s2) -> [Link]([Link])); // forEach with lambda
[Link](s -> [Link]([Link])); // Runnable with lambda (no need to implement Runnable) Runnable
r = () -> [Link]("Thread running!"); new Thread(r).start();

■ CASE STUDY: Employee Management System — Sorting & Config

Page 8
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

An HR system stores Employee objects in an ArrayList. Comparable implements natural ordering by employeeId. Three Comparators
provide flexible sorting: SortBySalary for payroll reports, SortByName for HR directories, SortByJoiningDate for seniority lists.
Lambda expressions replace verbose anonymous inner classes: [Link]((e1,e2) -> [Link] - [Link]) sorts in one line. A
[Link] file stores DB_URL, DB_USER, DB_PASSWORD — the Properties class loads this file at startup instead of
hardcoding credentials in code, making deployment across dev/staging/production seamless.

Page 9
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 5

Multithreading
Threads · Creating Threads · Thread Life Cycle · Pooling · Inter-thread Communication

5.1 Threads and Multithreading


Thread: The smallest unit of a process that can execute independently. All threads of a process share common memory (heap) but
each has its own stack.
Multithreading: Executing multiple threads simultaneously within one program. Maximises CPU utilisation — while one thread waits
for I/O, another thread runs.
Single-threaded process: One task at a time. Multi-threaded: Multiple tasks concurrently.
Advantages: (1) Better CPU utilisation, (2) Faster execution of complex programs, (3) Responsive GUIs (UI thread + background
thread), (4) Shared memory communication.

Thread Life Cycle (6 States)


State Description How to reach

NEW Thread object created but start() not called yet Thread t = new Thread()

RUNNABLE Ready to run or currently running — waiting for CPU After [Link]() called

BLOCKED Waiting to acquire a lock held by another thread Trying to enter synchronized block

WAITING Waiting indefinitely for another thread to act Calling wait(), join()

TIMED_WAITING Waiting for a specified time period Calling sleep(ms), wait(ms), join(ms)

TERMINATED Thread has completed execution or was terminated run() method finishes

Creating Threads — Two Ways


// Method 1: Extend Thread class

class MyThread extends Thread { public void run() { [Link]("Thread running: " +
[Link]().getName()); } } MyThread t = new MyThread(); [Link](); // DO NOT call run() directly —
use start()

// Method 2: Implement Runnable interface (PREFERRED)

class MyTask implements Runnable { public void run() { for(int i=0; i<5; i++) [Link](i + " from " +
[Link]().getName()); } } Thread t = new Thread(new MyTask()); [Link](); // OR with Lambda (Java
8+): new Thread(() -> [Link]("Lambda thread")).start();

Inter-thread Communication

wait(): Releases the lock and puts current thread into WAITING state. Another thread must call notify() to wake it.
notify(): Wakes ONE thread waiting on the same object. The awakened thread competes for the lock.
notifyAll(): Wakes ALL threads waiting on the same object.
Rule: wait(), notify(), notifyAll() must be called only from within a synchronized block/method. Otherwise →
IllegalMonitorStateException.
Thread Pooling: Creating threads is expensive. A thread pool maintains a fixed number of reusable threads. Use ExecutorService
([Link]) for production applications.

■ CASE STUDY: Video Streaming Platform (like YouTube)

Page 10
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

A video streaming backend uses multithreading extensively: Thread 1 handles video upload (long I/O task). Thread 2 runs video
encoding concurrently (CPU task). Thread 3 updates the database with video metadata. Thread 4 sends a confirmation email to the
uploader. Without multithreading, all 4 tasks would run sequentially — total time = sum of all. With multithreading, encoding starts
while upload is still in progress. Inter-thread communication (wait/notify) ensures encoding only starts AFTER upload completes:
upload thread calls notifyAll() when done, waking the encoding thread from wait().

Page 11
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 6

More on Multithreading
Suspending Threads · Resuming Threads · Deadlock · Stopping Threads · Deadlock Solutions

6.1 Suspending and Resuming Threads


suspend(): Moves a thread from RUNNING → BLOCKED/SUSPENDED state. The thread stops executing but is not terminated.
DEPRECATED — prone to deadlocks.
resume(): Moves a suspended thread back to RUNNABLE state. Only meaningful after suspend(). Also DEPRECATED.
Why deprecated? If a thread holds a lock when suspended, no other thread can acquire that lock → instant deadlock. The thread
that would call resume() may also need the same lock → deadlock.
Safe alternative: Use wait()/notify() or a boolean volatile flag: private volatile boolean paused = false; Check the flag inside run()
loop.

6.2 Deadlock
Deadlock: A situation where two or more threads are permanently blocked, each waiting for a lock held by the other. All affected
threads stop making progress.
Classic scenario: Thread T1 holds lock on Resource1, wants Resource2. Thread T2 holds lock on Resource2, wants Resource1.
Both wait forever.
4 Conditions for Deadlock (Coffman conditions): (1) Mutual Exclusion, (2) Hold and Wait, (3) No Preemption, (4) Circular Wait.

Deadlock Solutions
Solution How it works Example

Avoid Unnecessary Locks Only lock resources that truly need protection. ReduceRead-only
lock scope.
operations do not need synchronization.

Avoid Nested Locks Never acquire a second lock while holding the first. If T1 needs R1+R2, acquire both at once or release R1 before taking R2

Lock Ordering Always acquire locks in the same global order (e.g., R1
T1:
before
lock R1
R2)then
in ALL
[Link].
T2: lock R1 then R2. (not R2 then R1)

[Link]() Ensure one thread finishes before another starts accessing


[Link]();
shared
// wait
resources.
for t1 to finish, then t2 starts

tryLock() with timeout Use [Link](timeout) — if lock not acquired,


if([Link](1,
back off [Link]))
retry. { ... }

6.3 Stopping a Thread


stop() — DEPRECATED: Immediately kills thread, may leave objects in inconsistent state.
Safe method 1 — Boolean flag: private volatile boolean running = true; In run(): while(running) { ... }. To stop: [Link] = false;
Safe method 2 — interrupt(): [Link](); In run(): check [Link]() or catch InterruptedException in sleep().
Thread auto-terminates when run() method completes normally.

■ CASE STUDY: ATM Transaction Processing

An ATM system has two threads: TransactionThread (processes withdrawal/deposit) and PrintThread (prints receipt). Both threads
access shared Account objects. DEADLOCK scenario: TransactionThread locks account A then tries to lock account B.
Simultaneously, a transfer from B to A has PrintThread locking account B then trying to lock account A. Both wait forever. FIX:
Establish lock-ordering rule — always lock the account with the smaller ID first. Both threads acquire locks in the same order,
eliminating circular wait. The "Cancel" button on the ATM uses interrupt() to safely stop a pending transaction thread.

Page 12
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 7

Synchronization & Exception Handling


Thread Synchronization · synchronized keyword · Exception Types · try-catch-finally · Multithreaded Exception Handling

7.1 Thread Synchronization


Problem: When multiple threads access shared mutable data simultaneously, race conditions occur — final value depends on
thread execution order, leading to data corruption.
synchronized keyword: Ensures only ONE thread at a time can execute a critical section (synchronized method or block). The
thread acquires the object's monitor lock, executes, then releases.
Synchronized method: public synchronized void deposit(int amount) { ... } — lock is on "this" object.
Synchronized block: synchronized(objectRef) { ... } — finer-grained, locks only a specific object for a specific block. More efficient
than locking the whole method.
Static synchronized: public static synchronized void method() { ... } — lock is on the Class object, not an instance.

// Synchronization Example — Shared Table

class Table { synchronized void printTable(int n) { // Only one thread at a time for(int i=1; i<=5; i++) {
[Link](n * i); [Link](400); } } } // Without synchronized: outputs from t1 and t2 interleave
randomly // With synchronized: t1 completes all 5 lines, THEN t2 starts

7.2 Exception Handling


Exception: An unexpected event (runtime error) that disrupts normal program flow. When it occurs, an exception object is created
and thrown to the runtime system.
Checked Exceptions: Must be handled at compile time. Extended from Exception (not RuntimeException). E.g.: IOException,
SQLException, FileNotFoundException.
Unchecked Exceptions: Runtime exceptions — not required to be handled. E.g.: NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException, ClassCastException.
Error: Serious problems that applications should not try to catch. E.g.: StackOverflowError, OutOfMemoryError.

// Exception Handling Keywords

try { int result = 10 / 0; // ArithmeticException thrown here // Rest of try block skipped } catch
(ArithmeticException e) { [Link]("Error: " + [Link]()); // "/ by zero" } catch (Exception e)
{ [Link]("General error: " + e); // catch-all } finally { [Link]("Always executes —
cleanup here"); // close files, DB connections } // throw: manually throw exception if(age < 0) throw new
IllegalArgumentException("Age cannot be negative"); // throws: declare checked exceptions in method signature
public void readFile() throws IOException { ... }

Exception Handling in Multithreading

In a multithreaded program, exceptions in one thread do NOT affect other threads — each thread has its own execution stack.
Uncaught exceptions in a thread terminate that thread silently. Use [Link]() to handle uncaught
exceptions globally.
wait(), notify(), notifyAll() must be called from synchronized blocks — otherwise they throw IllegalMonitorStateException.
When a thread calls wait(), it releases the lock and enters WAITING state. When notify() is called, it moves to BLOCKED state
(waiting for lock) then RUNNABLE.

■ CASE STUDY: Online Flight Booking System

Page 13
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

A flight booking system handles thousands of concurrent requests. The seatBooking(int seatNo) method is synchronized — only one
user at a time can book a specific seat, preventing double-booking (race condition). Exception handling manages:
ArithmeticException (invalid fare calculation), ArrayIndexOutOfBoundsException (invalid seat number), IOException (payment
gateway timeout), SQLException (database connection failed). The finally block ALWAYS closes the database connection regardless
of success or failure — preventing connection leaks. A custom InsufficientSeatsException is thrown when all seats are booked: throw
new InsufficientSeatsException("Flight full — no seats available.");

Page 14
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 8

Swings — GUI Programming


JButton · JRadioButton · JTextArea · JComboBox · JTable · Event Handling

8.0 What is Swing?


Swing is Java's GUI (Graphical User Interface) toolkit — part of the [Link] package. It provides lightweight,
platform-independent UI components (JComponents).
vs AWT: Swing components are 100% Java (lightweight). AWT components are native OS widgets (heavyweight). Swing offers more
components and better look-and-feel consistency.
Key container: JFrame is the main application window. JPanel groups components. Components are added to JFrame or JPanel.
Event handling: User actions (click, type, select) generate Events. Listeners (ActionListener, ItemListener) respond to events by
implementing their methods.

Component Class Purpose Key Constructor / Method

Button JButton Clickable labeled button. Triggers ActionEvent onJButton("OK"),


click. addActionListener(al), setEnabled(bool)

Radio Button JRadioButton Mutually exclusive selection. Only one in a ButtonGroup


JRadioButton("Yes"),
can be selected.
ButtonGroup, setSelected(true)

Text Area JTextArea Multi-line text input/display field. Allows word wrap.
JTextArea(rows, cols), append(text), setText(), getText()

Combo Box JComboBox Dropdown list for selecting one item from multipleJComboBox(items[]),
options. addItem(), getSelectedItem()

Table JTable Displays data in rows and columns with [Link](data[][], headers[]), getValueAt(row,col)

Label JLabel Non-editable text or icon display. JLabel("Name:"), setFont(), setForeground(Color)

Text Field JTextField Single-line text input. JTextField(20), getText(), setText()

Check Box JCheckBox Binary on/off toggle. Multiple can be selected simultaneously.
JCheckBox("Java"), isSelected(), setSelected(true)

// JButton with ActionListener — Event Handling

import [Link].*; import [Link].*; import [Link].*; public class ButtonExample { public static
void main(String[] args) { JFrame frame = new JFrame("Button Demo"); JButton btn = new JButton("Click Me!");
JLabel label = new JLabel("Waiting..."); [Link](e -> [Link]("Button clicked!"));
[Link](btn, [Link]); [Link](label, [Link]); [Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE); [Link](true); } }

■ CASE STUDY: Student Registration Form

A college registration desktop application uses Swing: JTextField accepts student name and roll number. JRadioButton group
(Male/Female/Other) with ButtonGroup ensures only one gender is selected. JComboBox lists all available courses ([Link], BCA,
MBA). JCheckBox allows selecting multiple elective subjects. JTable displays the registered students in a grid with Name, Roll,
Course columns. A "Register" JButton with ActionListener validates inputs, inserts data, and refreshes the JTable. All components
are arranged in a JPanel with GridLayout.

Page 15
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 9

More on Swings
JColorChooser · JProgressBar · JSlider

9.1 JColorChooser
JColorChooser is a pre-built dialog that lets users select a colour from a GUI panel. Part of [Link] package. Extends
JComponent.
5 panes: Swatches (colour grid), HSV (Hue-Saturation-Value), HSL (Hue-Saturation-Lightness), RGB (Red-Green-Blue sliders), Hex
(hexadecimal input).
Usage: Color c = [Link](parent, "Choose Color", [Link]); Returns selected Color object (null if cancelled).
Real-life use: Paint/drawing applications, theme customisers, any app where users configure UI colors.

9.2 JProgressBar
JProgressBar shows progress of a task as a filled bar. Can be horizontal (default) or vertical. Can show percentage text.
Key methods: setValue(int), getValue(), setMinimum(int), setMaximum(int), setStringPainted(true) — shows % text,
setString("Uploading...") — custom text.
Usage pattern: Run the time-consuming task in a separate thread (SwingWorker). Update progress bar from that thread. Keeps UI
responsive.
Real-life use: File download/upload progress, installation wizards, data loading indicators.

9.3 JSlider
JSlider lets users select a numeric value by dragging a knob along a track. Supports orientation (HORIZONTAL/VERTICAL), min,
max, current value, tick marks, and labels.
Key constructors: JSlider(min, max), JSlider(orientation, min, max, initialValue).
Key methods: getValue(), setValue(int), setMajorTickSpacing(int), setMinorTickSpacing(int), setPaintTicks(true),
setPaintLabels(true), addChangeListener().
Real-life use: Volume control, brightness adjustment, zoom level, price range filter.

// JSlider + JProgressBar together

JSlider slider = new JSlider([Link], 0, 100, 50); [Link](20);


[Link](true); [Link](true); JProgressBar progress = new JProgressBar(0, 100);
[Link](50); [Link](true); // shows "50%" // Link slider to progress bar:
[Link](e -> [Link]([Link]()));

■ CASE STUDY: Media Player Application

A Java desktop media player uses all three advanced Swing components: JSlider (horizontal) shows playback position (0 to song
duration in seconds) — dragging it seeks to that position. JSlider (vertical) controls volume (0 to 100) with major ticks at 20, 40, 60,
80, 100. JProgressBar shows buffering progress — fills from 0% to 100% as the file loads from the internet. JColorChooser lets users
customise the player theme — background and text colour are changed dynamically using
[Link]().setBackground(chosenColor).

Page 16
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 10

Layouts
Layout Manager · BorderLayout · GridLayout · FlowLayout · BoxLayout · CardLayout

10.0 Layout Managers


A Layout Manager controls how components are positioned and sized within a container (JFrame, JPanel). Java provides several
built-in layout managers for different use cases.
Set layout: [Link](new GridLayout(3,3));
Default layouts: JPanel → FlowLayout. JFrame content pane → BorderLayout.

Layout How it arranges components Best for Key Constructor

FlowLayout Left to right in a row. Wraps to next line when full.


Button
Like words
bars, simple
in a paragraph.
toolbars. FlowLayout(), FlowLayout(align, hgap, vgap)

BorderLayout Divides container into 5 regions: NORTH, SOUTH,


Main
EAST,
app window
WEST, layout
CENTER.
(menu
Each
top,region
status
BorderLayout(),
holds
bottom,
onecontent
component.
add(comp,
center).
[Link])

GridLayout Equal-sized cells in rows and columns. Like a spreadsheet.


Calculators,Components
form-like interfaces
fill left-to-right,
with equal
GridLayout(rows,
top-to-bottom.
cells. cols), GridLayout(r,c,hgap,vgap)

BoxLayout Arranges components in a single row (X_AXIS) or


Vertical
columntoolbars,
(Y_AXIS).
stacked
Respects
panels.
component
BoxLayout(panel,
preferred sizes.
BoxLayout.Y_AXIS)

CardLayout Stacks components like a deck of cards. Only one


Wizard
card (component)
dialogs, tabbed-like
visible screens,
at a [Link]-by-step
CardLayout(),
Switch programmatically.
forms.
show(container, "cardName")

SpringLayout Positions components using spring-like constraints


Formbetween
layoutstheir
withedges.
alignedVery
labels
flexible,
and fields.
[Link],
complex. [Link] constr

// BorderLayout Example

JFrame frame = new JFrame("Layout Demo"); [Link](new BorderLayout()); [Link](new JButton("NORTH"),


[Link]); [Link](new JButton("SOUTH"), [Link]); [Link](new JButton("EAST"),
[Link]); [Link](new JButton("WEST"), [Link]); [Link](new JButton("CENTER"),
[Link]); // GridLayout — 3x3 Calculator Keypad JPanel keypad = new JPanel(new
GridLayout(3,3,2,2)); // 3 rows, 3 cols, 2px gaps for(int i=1; i<=9; i++) [Link](new
JButton([Link](i)));

■ CASE STUDY: IDE (Integrated Development Environment) GUI

A Java IDE like NetBeans combines multiple layouts: Outer JFrame uses BorderLayout: menu bar (NORTH), output console
(SOUTH), file explorer (WEST), code editor (CENTER), properties panel (EAST). The toolbar inside the NORTH panel uses
FlowLayout to arrange buttons left-to-right. The settings dialog uses GridLayout for label-field pairs (Language, Font, Theme in a neat
grid). The "New Project Wizard" uses CardLayout — each wizard step is a card; "Next" and "Back" buttons navigate between cards.
BoxLayout stacks panels vertically in the left file explorer.

Page 17
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 11

Managing Data using JDBC


JDBC Introduction · Driver Types · JDBC Architecture · Database Connectivity · CRUD Operations · Connection Interface

11.1 What is JDBC?


JDBC (Java Database Connectivity) is a standard Java API in [Link] package that provides a uniform interface for connecting
Java programs to relational databases (MySQL, Oracle, PostgreSQL, SQLite, Derby, etc.).
Before JDBC: ODBC was used — written in C, platform-dependent, not secure for Java. JDBC is 100% Java.
What JDBC enables: Connect to database, Execute SQL queries (SELECT/INSERT/UPDATE/DELETE), Process results, Manage
transactions.
Core JDBC components: DriverManager (manages drivers, creates connections), Connection (represents a session with the DB),
Statement (executes SQL), ResultSet (holds query results), PreparedStatement (pre-compiled SQL).

JDBC Driver Types


Type Name Description Advantage/Disadvantage

Type 1 JDBC-ODBC Bridge Bridges JDBC to ODBC API. Requires ODBC driver installed.
+ EasyDeprecated.
to use – Slow (double translation), requires ODBC setup

Type 2 Native API Converts JDBC calls to native database API calls. Partly Java.
+ Better performance – Requires native library on each client machine

Type 3 Network Protocol Sends JDBC calls through middleware application server.+Pure
DB-independent,
Java. no native lib – Needs extra server tier

Type 4 Thin Driver Pure Java. Directly converts JDBC to database-specific network
+ Fastest,
protocol.
no extra software – DB-specific, one driver per DB

Steps for Database Connectivity

Step 1 — Load/Register Driver: [Link]("[Link]"); (modern JDBC auto-loads drivers via ServiceLoader)
Step 2 — Create Connection: Connection con = [Link]("jdbc:mysql://localhost:3306/mydb", "user", "pass");
Step 3 — Create Statement: Statement stmt = [Link]();
Step 4 — Execute Query: ResultSet rs = [Link]("SELECT * FROM students"); or int rows =
[Link]("INSERT INTO...");
Step 5 — Process Results: while([Link]()) { String name = [Link]("name"); int age = [Link]("age"); }
Step 6 — Close Resources: [Link](); [Link](); [Link](); (or use try-with-resources)

// JDBC CRUD Operations

String url = "jdbc:mysql://localhost:3306/school"; Connection con = [Link](url, "root",


"pass"); Statement stmt = [Link](); // CREATE [Link]("INSERT INTO students VALUES(1,
'Alice', 20)"); // READ ResultSet rs = [Link]("SELECT * FROM students"); while([Link]())
[Link]([Link](1)+": "+[Link](2)); // UPDATE [Link]("UPDATE students SET age=21
WHERE id=1"); // DELETE [Link]("DELETE FROM students WHERE id=1"); [Link]();

■ CASE STUDY: University Student Database System

A university uses JDBC to connect its Java application to a MySQL database containing student records. On application startup:
[Link] loads the MySQL Type-4 driver (pure Java, fastest). Admission form: PreparedStatement (prevents SQL injection)
inserts new student: "INSERT INTO students (name, roll, branch) VALUES (?, ?, ?)". Grade report: ResultSet retrieves marks for all
subjects for a given student ID. Fee payment update: executeUpdate() marks fee as paid for the semester. Connection pooling (via
HikariCP) maintains 10 ready connections, avoiding connection setup overhead for each request. Finally block ensures connections
are always closed to prevent resource leaks.

Page 18
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 12

More on JDBC
Statement Interface · PreparedStatement · ResultSet Interface · ResultSetMetaData · DatabaseMetaData

12.1 Statement Interface


Statement: Used to execute static SQL queries. Creates a new execution plan for each call.
execute(sql): For any SQL (SELECT/INSERT/UPDATE). Returns boolean — true if ResultSet, false if row count.
executeQuery(sql): For SELECT statements. Returns ResultSet containing the results.
executeUpdate(sql): For INSERT, UPDATE, DELETE, CREATE TABLE. Returns int (number of rows affected).
executeBatch(): Execute a group of SQL statements together for better performance. Use addBatch(sql) to queue, executeBatch()
to run all.

12.2 PreparedStatement
PreparedStatement is a pre-compiled SQL statement with placeholders (?). Compiled once, executed many times with different
parameters.
Advantages over Statement: (1) Prevents SQL Injection — user input treated as data, not SQL. (2) Better performance for repeated
queries. (3) Handles data types automatically.
SQL Injection example — vulnerable: "SELECT * FROM users WHERE name='" + userInput + "'" → Input "x' OR 1=1 --" bypasses
auth.
PreparedStatement — safe: PreparedStatement ps = [Link]("SELECT * FROM users WHERE name=?");
[Link](1, userInput); — SQL injection impossible.
Set methods: setInt(pos,val), setString(pos,val), setDouble(pos,val), setDate(pos,val), setNull(pos,type).

12.3 ResultSet and ResultSetMetaData


ResultSet: Holds rows returned by a SELECT query. Cursor starts before first row — use next() to advance.
Navigation types: TYPE_FORWARD_ONLY (default, cursor moves only forward), TYPE_SCROLL_INSENSITIVE
(forward/backward, not affected by DB changes), TYPE_SCROLL_SENSITIVE (forward/backward, reflects DB changes).
Get methods: getInt("col"), getString("col"), getDouble("col"), getDate("col"), getBoolean("col"). Can also use column index:
getString(1).
ResultSetMetaData: rsmd = [Link](); → getColumnCount(), getColumnName(i), getColumnTypeName(i), getTableName(i).
Used when you don't know the query structure in advance.
DatabaseMetaData: dbmd = [Link](); → getDriverName(), getDriverVersion(), getUserName(),
getDatabaseProductName(). Used for introspection of DB capabilities.

// PreparedStatement + ResultSetMetaData

// PreparedStatement — safe insertion String sql = "INSERT INTO products (name, price, qty) VALUES (?,?,?)";
PreparedStatement ps = [Link](sql); [Link](1, "Laptop"); [Link](2, 45999.0);
[Link](3, 50); [Link](); // ResultSetMetaData — explore unknown table structure ResultSet rs =
[Link]("SELECT * FROM orders"); ResultSetMetaData rsmd = [Link]();
[Link]("Columns: " + [Link]()); for(int i=1; i<=[Link](); i++)
[Link]([Link](i) + " : " + [Link](i));

■ CASE STUDY: E-Commerce Order Management

An e-commerce platform processes thousands of orders daily using JDBC. PreparedStatement handles all insert/update operations
— especially critical for the payment module where hackers commonly attempt SQL injection via tampered order IDs. A bulk order
import feature uses executeBatch() — adds 500 product inserts to a batch, executes in one round-trip instead of 500 separate calls
(10x faster). ResultSetMetaData dynamically generates export reports — the system does not hardcode column names; it reads them
from [Link](i) to build CSV headers automatically. DatabaseMetaData checks the connected database version
before running version-specific queries.

Page 19
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 13

Network Programming
Networking Concepts · Socket Class · ServerSocket Class · URL Class · TCP/IP

13.1 Java Networking Fundamentals


IP Address: A unique numerical label (e.g., [Link]) identifying a device on a network. IPv4: 32-bit (4 octets). IPv6: 128-bit.
Port Number: A 16-bit number (0-65535) that identifies a specific application/service on a host. Port 80 = HTTP, 443 = HTTPS, 21 =
FTP, 22 = SSH, 3306 = MySQL.
Protocol: Rules for communication. TCP (reliable, connection-oriented, in-order delivery). UDP (unreliable, connectionless, fast —
used for video streaming, gaming).
Socket: An endpoint of a two-way communication link between two programs over a network. A socket = IP Address + Port Number.
MAC Address: Hardware address of a network interface card (NIC). Unique to each device.

13.2 Socket Class


[Link] implements the client side of a TCP connection. Each Socket object is connected to exactly one remote host.
Constructor: Socket("hostname", port) e.g., Socket("localhost", 5000)
Key methods: getInputStream() — read data from server, getOutputStream() — send data to server, getInetAddress() — server's IP,
getPort() — server's port, close() — disconnect.
Communication streams: DataInputStream dis = new DataInputStream([Link]()); BufferedReader br = new
BufferedReader(new InputStreamReader([Link]()));

13.3 ServerSocket Class


[Link] waits for clients to connect (server side). Binds to a port and listens.
Constructor: ServerSocket(port) e.g., ServerSocket(5000)
accept(): Blocks and waits for a client connection. When a client connects, returns a new Socket for that client. The ServerSocket
continues listening for more clients.
Pattern: ServerSocket ss = new ServerSocket(5000); Socket s = [Link](); (blocking call) Then use
[Link]()/getOutputStream() to communicate.
Multi-client: For each accepted connection, spawn a new Thread to handle that client, while the main thread calls accept() again.

// Simple Client-Server Communication

// SERVER SIDE ServerSocket ss = new ServerSocket(6000); Socket s = [Link](); // Wait for client
DataInputStream dis = new DataInputStream([Link]()); String msg = [Link](); // Read from client
[Link]("Client says: " + msg); [Link](); [Link](); // CLIENT SIDE Socket s1 = new
Socket("localhost", 6000); // Connect to server DataOutputStream dos = new
DataOutputStream([Link]()); [Link]("Hello Server!"); // Send to server [Link]();
[Link]();

13.4 URL Class


URL (Uniform Resource Locator) is a pointer to a resource on the web. Structure: Protocol://Hostname:Port/Path?Query#Fragment
[Link] class represents a URL and provides methods to extract its components.
Key methods: getProtocol(), getHost(), getPort(), getPath(), getFile(), getQuery(), getRef(), openConnection() — returns
URLConnection for reading the resource.
InetAddress: [Link]() — local machine's IP and hostname. [Link]("[Link]") —
resolves domain to IP via DNS.

■ CASE STUDY: Chat Application

Page 20
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

A simple Java multi-client chat server uses: ServerSocket binds to port 9090 and listens. For each connecting client, accept() returns
a Socket, and a new ClientHandler thread is spawned. ClientHandler reads messages via DataInputStream and broadcasts to all
connected clients via their DataOutputStreams. Client application: Socket connects to server IP + port 9090. Two threads: one reads
user keyboard input and sends via DataOutputStream; another continuously reads incoming messages via DataInputStream and
displays them. The URL class parses file attachment links shared in chat: getFile() extracts filename, openConnection() downloads it.

Page 21
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

UNIT 14

More on Network Programming


URL & URLConnection · DatagramSocket · DatagramPacket · UDP Socket Programming

14.1 URL and URLConnection Class


URL class: Represents a Uniform Resource Locator. Components: Protocol (https), Hostname ([Link]), Port (443), Path
(/lpuums/home), Query (?id=5), Fragment (#section2).
URLConnection: [Link]() returns a URLConnection. Can read response headers and content.
Reading a webpage: URLConnection conn = new URL("[Link] BufferedReader br = new
BufferedReader(new InputStreamReader([Link]()));
Key methods: getContentType(), getContentLength(), getDate(), getLastModified(), getHeaderField("key"), getInputStream().

14.2 UDP — DatagramSocket and DatagramPacket


UDP (User Datagram Protocol): Connectionless protocol. No handshake, no guaranteed delivery, no ordering. Faster than TCP.
Packets called datagrams.
When to use UDP: Real-time applications where speed > reliability — video streaming, online gaming, VoIP, DNS queries, live
sensor data.
DatagramSocket: Used for both sending and receiving UDP datagrams. No connection concept.
DatagramPacket: Wraps the data payload + destination/source address + port. For sending: specify data + destination. For
receiving: specify buffer — address/port filled in by receive().

// UDP Sender & Receiver

// SENDER ([Link]) DatagramSocket ds = new DatagramSocket(); String str = "Hello via UDP"; byte[] buf =
[Link](); InetAddress addr = [Link]("localhost"); DatagramPacket dp = new
DatagramPacket(buf, [Link], addr, 3000); [Link](dp); // Fire and forget! [Link](); // RECEIVER
([Link]) DatagramSocket ds = new DatagramSocket(3000); // Listen on port 3000 byte[] buf = new
byte[1024]; DatagramPacket dp = new DatagramPacket(buf, 1024); [Link](dp); // Blocks until data arrives
String received = new String([Link](), 0, [Link]()); [Link]("Received: " + received);

TCP vs UDP — When to Use Which


Feature TCP UDP

Connection Connection-oriented (3-way handshake) Connectionless — no setup needed

Reliability Guaranteed delivery, ordered, no duplicates No guarantee — packets may be lost/reordered

Speed Slower (overhead for acknowledgements) Faster (minimal overhead)

Use cases HTTP/S, SMTP, FTP, SSH, JDBC, file transfer DNS, VoIP, live video, online gaming, IoT sensors

Java Classes Socket, ServerSocket DatagramSocket, DatagramPacket

Error handling Automatic retransmission Application must handle errors if needed

■ CASE STUDY: Multiplayer Online Game Server

An online multiplayer game uses both TCP and UDP: TCP (Socket/ServerSocket) handles login, player registration, inventory
updates, and game state saves — data that MUST be accurate and delivered. UDP (DatagramSocket) transmits real-time position
updates 60 times per second — if a position packet is lost, the next update corrects it anyway. Using TCP for positions would add
40ms+ latency from acknowledgements, making the game unplayable. The game server uses URLConnection to fetch the latest
patch notes from the company website and display them in the game lobby. The URL class parses resource URLs for loading game
assets (textures, sounds) from CDN servers.

Page 22
ECAP615 — Programming in Java | Unit-wise Key Notes, Case Studies & Applications
Harjinder Kaur | Lovely Professional University

COMPREHENSIVE UNIT SUMMARY

Unit Topic Core Concepts Key Real-World Use

1 Introduction JVM/JDK/JRE, OOP, Data Types, Operators, Wrapper Classes, Nested Classes
Platform-independent enterprise apps, Android development

2 Arrays & Strings 1D/2D Arrays, String immutability, String Pool, StringBuffer vs StringBuilder,
Product
Inheritance,
catalogues,
Access
textSpecifiers
processing, OOP-based system desi

3 Collection Framework ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, ListIterator Hospital queues, shopping carts, search indexes

4 More Collections Comparable, Comparator, Properties class, Lambda Expressions Employee sorting, configuration management, functional prog

5 Multithreading Thread states, extends Thread, implements Runnable, wait/notify, threadVideo


pooling
processing, concurrent server requests, real-time syste

6 More Multithreading suspend/resume (deprecated), Deadlock, deadlock prevention, stopping ATM


threads
systems, concurrent database access, resource-sharing

7 Synchronization synchronized methods/blocks, Exception types (checked/unchecked), try-catch-finally,


Banking transactions,
throw/throws
flight booking, multi-user applications

8 Swings JButton, JRadioButton, JTextArea, JComboBox, JTable, Event Handling,Desktop


ActionListener
forms, registration systems, admin dashboards

9 More Swings JColorChooser, JProgressBar, JSlider Media players, file download indicators, colour-picker tools

10 Layouts BorderLayout, GridLayout, FlowLayout, BoxLayout, CardLayout, LayoutManager


IDEs, wizard dialogs, calculator UIs, complex desktop apps

11 JDBC Basics JDBC drivers (Types 1-4), DB connectivity steps, CRUD operations, Statement,
University
ResultSet
records, inventory management, ERP systems

12 More JDBC PreparedStatement (SQL injection prevention), ResultSetMetaData, DatabaseMetaData,


E-commerce order
executeBatch
processing, bulk imports, secure login sys

13 Network Programming IP/Port/Protocol, Socket, ServerSocket, TCP client-server, URL class, InetAddress
Chat applications, remote monitoring, web scraping

14 More Networking URL/URLConnection, DatagramSocket, DatagramPacket, UDP programming,


OnlineTCP
gaming,
vs UDP
VoIP,
comparison
live streaming, IoT sensor networks

These notes cover all 14 units of ECAP615 Programming in Java from Lovely Professional University. Every concept is
paired with a simple analogy, code example, and real-world case study to bridge theory and practice. Master the
fundamentals (Units 1-4), concurrency (Units 5-7), GUI (Units 8-10), and backend integration (Units 11-14) to become a
well-rounded Java developer.

Page 23

You might also like