ECAP615 Java UnitWise Notes
ECAP615 Java UnitWise Notes
ECAP615
Programming in Java
Unit-wise Key Notes · Concept Explanations · Case Studies · Code Examples · Real-Life Applications
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
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.
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.
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
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 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.
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
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
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().
StringBuffer vs StringBuilder
Feature String StringBuffer StringBuilder
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.
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
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
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.
Null Allows one null Does NOT allow null (throws NullPointerException)
Use when Fast lookup, order not needed Need sorted unique elements
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
// 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
// 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();
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
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
class MyThread extends Thread { public void run() { [Link]("Thread running: " +
[Link]().getName()); } } MyThread t = new MyThread(); [Link](); // DO NOT call run() directly —
use start()
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.
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.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)
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
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
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 { ... }
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.
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
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)
Check Box JCheckBox Binary on/off toggle. Multiple can be selected simultaneously.
JCheckBox("Java"), isSelected(), setSelected(true)
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); } }
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.
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
// BorderLayout Example
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
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
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)
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.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).
// 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));
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
// 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]();
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
// 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);
Use cases HTTP/S, SMTP, FTP, SSH, JDBC, file transfer DNS, VoIP, live video, online gaming, IoT sensors
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
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
9 More Swings JColorChooser, JProgressBar, JSlider Media players, file download indicators, colour-picker tools
11 JDBC Basics JDBC drivers (Types 1-4), DB connectivity steps, CRUD operations, Statement,
University
ResultSet
records, inventory management, ERP systems
13 Network Programming IP/Port/Protocol, Socket, ServerSocket, TCP client-server, URL class, InetAddress
Chat applications, remote monitoring, web scraping
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