ECAP615 — Programming in Java Exam Notes | Lovely Professional University
ECAP615
Programming in Java
Exam Preparation Notes
All 14 Units — Handwritten-Style Summary
Lovely Professional University
Page 1 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 01 — Introduction to Java
1.1 What is Java?
▶ Core Idea
Java is a high-level, object-oriented programming language developed by Sun Microsystems in
1995. It was originally named 'OAK'. James Gosling is the father of Java. The big deal about Java is
that it compiles to bytecode — a platform-independent format — which runs on any machine that
has a JVM. This is the famous 'Write Once, Run Anywhere' principle.
▶ Key Points
• Java is object-oriented, platform-independent, robust, secure, and multithreaded.
• 4 OOP pillars: Inheritance, Encapsulation, Polymorphism, Dynamic Binding.
• Bytecode is interpreted by JVM — not OS-specific machine code.
• Java has no explicit pointers, reducing memory bugs.
• Automatic garbage collection manages memory deallocation.
▶ Why It Matters / Real Example
💡reader
Example: Think of Java bytecode like a PDF — you write it once and any machine with a PDF
(JVM) can open it. That's platform independence in a nutshell.
🎯Compare
Likely Exam Q: Explain the features of Java that make it platform-independent and robust. /
Java and C++.
1.2 Java Platforms / Editions
▶ Key Points
• Java SE (Standard Edition) — core language for general programming.
• Java EE (Enterprise Edition) — large-scale, multi-tier, networked apps.
• Java ME (Micro Edition) — embedded systems and mobile devices.
• JavaFX — rich internet applications with UI API.
🎯 Likely Exam Q: Name and explain the four editions/platforms of Java.
1.3 JDK, JRE, and JVM — The Holy Trinity
▶ Core Idea
These three are always confused. Think of it as layers: JDK is the full toolbox (contains JRE). JRE
is the runtime environment (contains JVM). JVM is the actual engine that executes bytecode. JDK
⊃ JRE ⊃ JVM.
▶ Key Points
• JDK (Java Development Kit) — compiler (javac), debugger, and JRE. Used to build Java
programs.
• JRE (Java Runtime Environment) — class libraries + JVM. Used to run Java programs.
• JVM (Java Virtual Machine) — loads, verifies, and executes bytecode. Platform-dependent in
implementation but makes Java platform-independent.
Page 2 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
• JVM components: ClassLoader, Method Area, Heap, Stack, PC Registers, Execution Engine,
Native Method Interface.
• javac compiles .java → .class (bytecode); java command runs .class using JVM.
▶ JVM Architecture Summary
• ClassLoader: loads class files (Bootstrap, Extension, System loaders).
• Bytecode Verifier: ensures code is safe to execute.
• Execution Engine: runs bytecode (uses JIT compiler for performance).
• Heap: stores all objects and arrays.
• Stack: stores local variables and method call frames, one per thread.
💡bytecode
Example: When you type 'java MyProgram', JVM starts, ClassLoader loads [Link],
verifier checks it, and execution engine runs it.
🎯platform-independent.
Likely Exam Q: Differentiate JDK, JRE, and JVM with a diagram. Explain how JVM makes Java
1.4 Data Types in Java
▶ Key Points
• Primitive types: boolean (1 bit), byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes), float (4
bytes), double (8 bytes), char (2 bytes).
• Non-primitive types: Classes, Interfaces, Arrays — these are reference types.
• Default values: int=0, boolean=false, float=0.0f, char='\u0000', object reference=null.
• char uses Unicode (0 to 65,535), not ASCII. This is why it is 2 bytes.
🎯difference
Likely Exam Q: List all primitive data types in Java with sizes and default values. What is the
between primitive and non-primitive?
1.5 Operators in Java
▶ Key Points
• Unary: ++, -- (increment/decrement), ! (negation).
• Arithmetic: +, -, *, /, % (modulus).
• Relational: ==, !=, <, >, <=, >=.
• Logical: && (AND), || (OR), ! (NOT).
• Bitwise: &, |, ^, ~, <<, >>, >>>.
• Ternary: condition ? valueIfTrue : valueIfFalse (takes 3 operands).
• Assignment: =, +=, -=, *=, /=, etc.
• Operator precedence: postfix → prefix → arithmetic → shift → relational → equality → bitwise →
logical → ternary → assignment.
🎯operator?
Likely Exam Q: Explain operator precedence in Java with examples. What is the ternary
1.6 Wrapper Classes, Autoboxing & Unboxing
▶ Core Idea
Basically, sometimes you need to treat a primitive (like int) as an object — for example, when using
collections like ArrayList which only accept objects. Wrapper classes do exactly that. Each primitive
has a corresponding wrapper: int → Integer, char → Character, double → Double, etc.
Page 3 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
▶ Key Points
• 8 wrapper classes: Byte, Short, Integer, Long, Float, Double, Character, Boolean.
• Autoboxing: automatic conversion of primitive → wrapper. e.g., Integer x = 5; (compiler boxes the
int automatically).
• Unboxing: automatic conversion of wrapper → primitive. e.g., int n = x + 1; (compiler unboxes x).
• Wrapper classes are immutable — once created, value cannot change.
• Useful methods: [Link](), [Link](), [Link]().
💡unboxing
Example: Integer x = 12; // autoboxing — compiler does [Link](12) int y = x + 5; //
— compiler does [Link]()
🎯unboxing
Likely Exam Q: What are wrapper classes and why are they needed? Explain autoboxing and
with code examples.
1.7 Nested Classes
▶ Core Idea
A nested class is simply a class defined inside another class. This improves code organization,
increases encapsulation, and is useful when a class is only relevant to one other class. Think of it
like a private folder inside a folder.
▶ Key Points
• Static Nested Class: declared static. Can't access instance members of outer class. Accessed
via outer class name: [Link].
• Inner Class (non-static): has access to all outer class members including private. Requires outer
class object to instantiate.
• Anonymous Inner Class: no name, used to implement an interface or extend a class inline. Very
common for event handling.
• Local Inner Class: defined inside a method. Can only be instantiated within that method.
💡innerExample:
class
Person p = new Person() { void eat() { [Link]("eating"); } }; // anonymous
🎯classes
Likely Exam Q: Differentiate static nested class vs inner class. Explain anonymous inner
with an example.
Page 4 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 02 — Arrays and Strings
2.1 Arrays
▶ Core Idea
An array stores multiple values of the same type under a single variable name. In Java, arrays are
objects, dynamically allocated on the heap. The index always starts from 0, and the length is fixed
once created.
▶ Key Points
• Declaration: int[] arr; OR int arr[];
• Creation: int[] arr = new int[5]; — allocates memory for 5 integers, initialized to 0.
• Array literal: int[] arr = {1, 2, 3, 4, 5}; — size inferred automatically.
• Accessing: arr[0], arr[1], …, arr[n-1]. Using [Link] gives the total count.
• 2D Array syntax: int[][] matrix = new int[3][4]; — 3 rows, 4 columns.
• Multidimensional: Total elements = product of all dimensions. int[10][20] = 200 elements.
• Arrays implement Cloneable and Serializable. Direct superclass is Object.
int[] a = new int[5]; a[0] = 10; a[1] = 20; for(int i=0; i<[Link]; i++)
[Link](a[i]);
🎯andLikely Exam Q: Write a program to multiply two matrices / find max and min in array / declare
initialize a 2D array.
2.2 Strings
▶ Core Idea
Strings in Java are objects, not primitives — and they're immutable, meaning once created they
can't change. Every time you modify a string a brand new String object is created. Java optimizes
memory with a String Constant Pool in the heap.
▶ Key Points
• Creating with literal: String s = "hello"; — stored in String Constant Pool. Same value reuses the
same object.
• Creating with new: String s = new String("hello"); — always creates a new object in heap
memory.
• Important methods: length(), concat(), indexOf(), toUpperCase(), toLowerCase(), equals(),
equalsIgnoreCase(), compareTo(), contains(), charAt(), substring().
• equals() compares values; == compares references (memory addresses).
• compareTo() returns 0 if equal, <0 if less, >0 if greater (lexicographic comparison).
• + operator is overloaded for String concatenation — the only operator overloading in Java.
💡immutable!
Example: String s = "Hello"; [Link](); // returns "HELLO" but s is still "Hello" —
String s2 = [Link](" World"); // new String created
🎯methods
Likely Exam Q: Explain why Strings are immutable in Java. Demonstrate at least 5 String
with examples.
Page 5 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
2.3 StringBuffer vs StringBuilder
▶ Core Idea
Both StringBuffer and StringBuilder are mutable (editable) string classes — unlike String. The key
difference is thread-safety: StringBuffer is synchronized (thread-safe but slower), while
StringBuilder is not synchronized (faster, use when single-threaded).
▶ Key Points
• StringBuffer — synchronized, thread-safe. Introduced in Java 1.2.
• StringBuilder — non-synchronized, better performance. Introduced in Java 1.5.
• Both have default capacity of 16. When exceeded: new capacity = (old capacity × 2) + 2.
• Common methods for both: append(), insert(), replace(), delete(), reverse(), length(), capacity(),
charAt().
• Use StringBuilder in single-threaded code for better performance.
💡World"
Example: StringBuffer sb = new StringBuffer("Hello"); [Link](" World"); // sb is now "Hello
— no new object! [Link](); // "dlroW olleH"
🎯methods
Likely Exam Q: Differentiate StringBuffer and StringBuilder. Write a program showing at least 3
of StringBuffer.
2.4 Access Specifiers
▶ Key Points
• private — only within the declared class.
• default (no modifier) — within the same package only.
• protected — same package + subclasses in other packages.
• public — accessible everywhere.
Accessibility from narrowest to widest: private < default < protected < public.
🎯accessible.
Likely Exam Q: Explain all four access modifiers with examples showing what is and isn't
2.5 Inheritance
▶ Core Idea
Inheritance lets a new class (subclass/child) reuse methods and fields from an existing class
(superclass/parent). The extends keyword is used. It represents an IS-A relationship — a Dog IS-A
Animal. The idea is to avoid rewriting code.
▶ Key Points
• Single Inheritance — one subclass from one superclass. Example: Dog extends Animal.
• Multilevel Inheritance — chain: BabyDog extends Dog extends Animal.
• Hierarchical Inheritance — multiple subclasses from one superclass.
• Multiple Inheritance — not supported with classes in Java (to avoid diamond problem). Achieved
via interfaces.
• Hybrid Inheritance — combination of single and multiple, achieved only through interfaces.
• A subclass inherits all non-private members (fields, methods, nested classes). Constructors are
NOT inherited — but parent constructor can be called via super().
• Default superclass for every class is Object (unless explicitly specified otherwise).
💡{ [Link]("Woof!");
Example: class Dog extends Animal { // Dog inherits eat() from Animal, adds bark()
}}
void bark()
Page 6 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
🎯support
Likely Exam Q: Write a Java program demonstrating multilevel inheritance. Why doesn't Java
multiple inheritance with classes?
Page 7 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 03 — Collection Framework
3.1 ArrayList
▶ Core Idea
Think of ArrayList as a smarter, resizable array. It's in [Link] and extends AbstractList. Unlike a
regular array, you don't need to specify size upfront — it grows automatically. But here's the catch:
it doesn't work with primitives directly; you need wrapper types like Integer instead of int.
▶ Key Points
• Maintains insertion order. Allows duplicates. Non-synchronized (not thread-safe). Random
access by index.
• Backed by a regular array internally. Default initial capacity is 10.
• add(element) — appends. add(index, element) — inserts at index.
• get(index) — retrieves. set(index, value) — updates.
• remove(index) or remove(object) — deletes. size() — returns count.
• [Link](list) — sorts in ascending natural order.
• Iteration: use for-each loop or Iterator.
ArrayList<String> cars = new ArrayList<>(); [Link]("BMW");
[Link]("Ford"); [Link](0, "Audi"); // change BMW to Audi
[Link](1); // remove Ford [Link](cars); // [Audi]
🎯difference
Likely Exam Q: Write a program to add, remove, and sort elements in ArrayList. What is the
between ArrayList and LinkedList?
3.2 ListIterator
▶ Key Points
• ListIterator allows bidirectional traversal of a List (unlike basic Iterator which is forward-only).
• Obtained via [Link]().
• Forward methods: hasNext(), next(), nextIndex().
• Backward methods: hasPrevious(), previous(), previousIndex().
• Supports all CRUD operations during iteration.
🎯example.
Likely Exam Q: What is ListIterator? How is it different from Iterator? Show its methods with an
3.3 LinkedList
▶ Core Idea
LinkedList is a doubly linked list — each node holds data plus references to the previous and next
node. Great for frequent insertions/deletions at the beginning or end but slower at random access
(no direct indexing — you have to traverse from head).
▶ Key Points
• Implements List and Deque interfaces. Inherits AbstractSequentialList.
• addFirst() / addLast(), removeFirst() / removeLast(), getFirst() / getLast().
Page 8 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
• add(element) — adds to end. add(index, element) — inserts at position.
• Allows null and duplicate elements.
💡[Link]("Mango");
Example: LinkedList<String> items = new LinkedList<>(); [Link]("Apple");
[Link](); // removes Apple
🎯 Likely Exam Q: Compare ArrayList and LinkedList in terms of performance and use cases.
3.4 TreeSet
▶ Core Idea
TreeSet stores elements in sorted (ascending) order, using a tree data structure underneath. No
duplicates, no nulls, and not synchronized. It's like a sorted set that guarantees order automatically.
▶ Key Points
• Implements NavigableSet → SortedSet → Set hierarchy.
• add(), remove(), addAll(), removeAll() for manipulation.
• first() / last() — get extremes. pollFirst() / pollLast() — get and remove extremes.
• higher(e), lower(e), ceiling(e), floor(e) — navigation methods.
• headSet(e) — all elements before e. tailSet(e) — all elements from e onward.
• Uses compareTo() (not equals()) for comparisons. Time complexity of add/remove: O(log n).
💡[Link](ts);
Example: TreeSet<Integer> ts = new TreeSet<>(); [Link](100); [Link](50); [Link](150);
// [50, 100, 150] — auto sorted!
🎯the Likely Exam Q: What data structure does TreeSet use internally? Write a program and show
output of adding elements in random order.
3.5 PriorityQueue
▶ Core Idea
PriorityQueue does NOT maintain insertion order like a normal queue. Instead, elements are
retrieved based on their priority (natural ordering by default, or a custom Comparator). The head of
the queue always has the smallest (highest priority) element.
▶ Key Points
• Extends AbstractQueue. Not thread-safe. Cannot store null elements.
• add() or offer() — inserts element (offer() returns false if queue is full, add() throws exception).
• peek() — view head element without removing. poll() — retrieve and remove head. remove() —
removes specific element.
• Cannot create PriorityQueue of non-comparable objects without a Comparator.
💡[Link](12);
Example: PriorityQueue<Integer> pq = new PriorityQueue<>(); [Link](14); [Link](11);
[Link]([Link]()); // 11 — smallest element at head
🎯 Likely Exam Q: Explain PriorityQueue with methods. How is it different from a regular Queue?
Page 9 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 04 — More on Collection Framework
4.1 Comparable vs Comparator Interface
▶ Core Idea
Both are used for sorting custom objects. The key difference: Comparable is built into the class
itself (natural ordering), while Comparator is an external class you write separately (custom
ordering). Think of Comparable as 'I know how to sort myself', and Comparator as 'I'll tell you how
to sort them'.
▶ Key Points — Comparable
• From [Link] package. Method: compareTo(Object o) — returns negative, zero, or positive.
• The class itself implements Comparable. Modifies the original class.
• One sorting sequence only. Used with [Link](list).
▶ Key Points — Comparator
• From [Link] package. Methods: compare(Object o1, Object o2) and equals(Object obj).
• Written as a separate class. Does not modify the original class.
• Multiple sorting sequences possible (by name, age, etc.). Used with [Link](list,
comparator).
💡Comparable<Stu>
Example: // Comparable: Student class sorts by roll number class Stu implements
{ public int compareTo(Stu s) { return [Link] - [Link]; }} // Comparator: external
class sorts by age class SortByAge implements Comparator<Stu> { public int compare(Stu s1, Stu
s2) { return [Link] - [Link]; }}
🎯do they
Likely Exam Q: Write programs demonstrating Comparable and Comparator interfaces. How
differ?
4.2 Properties Class
▶ Key Points
• Represents a persistent set of key-value pairs where both key and value are Strings.
• Part of [Link]. Subclass of Hashtable.
• Can be loaded from / stored to a .properties file.
• setProperty(key, value) / getProperty(key) — basic operations.
• load(reader) — reads from file. store(writer, comments) — writes to file.
• [Link]() — retrieves all JVM system properties.
• Multiple threads can share a single Properties object (thread-safe).
🎯 Likely Exam Q: How do you read and write to a .properties file using the Properties class?
4.3 Lambda Expressions (Java 8+)
▶ Core Idea
Lambda expressions are basically anonymous functions — a shortcut to write implementations of
functional interfaces without the verbose anonymous inner class syntax. They were introduced in
Java 8 and make code cleaner and more functional.
Page 10 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
▶ Key Points
• Syntax: parameter -> expression OR (param1, param2) -> expression.
• For multiple statements: (params) -> { statement1; statement2; return value; }
• Zero parameters: () -> expression
• Work with functional interfaces (interfaces with exactly one abstract method).
• Cannot contain variable assignments or if/for statements in simple form — use code block.
// Simple: print all elements [Link](n ->
[Link](n)); // Two parameters via functional interface
FuncInter1 add = (int x, int y) -> x + y;
[Link]([Link](10, 3)); // 13
🎯of lambda
Likely Exam Q: Write a lambda expression to filter even numbers from a list. Explain the syntax
expressions with examples.
Page 11 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 05 — Multithreading
5.1 Threads and Multithreading
▶ Core Idea
A thread is the smallest unit of a process that can run independently. Multithreading means multiple
threads run concurrently, sharing the same memory space. This is how Java handles things like
downloading a file while showing a progress bar at the same time.
▶ Key Points
• Thread — lightweight sub-process. Multiple threads share heap memory but have their own
stack.
• Multithreading maximizes CPU utilization. If one thread is blocked (e.g., waiting for I/O), another
can run.
• [Link] class creates and manages threads. Runnable interface provides the run()
method.
• Threads are independent — an exception in one thread doesn't crash others.
🎯process
Likely Exam Q: What are the advantages of multithreading? What is the difference between a
and a thread?
5.2 Creating Threads — Two Ways
▶ Method 1: Extending Thread class
• Create a class that extends Thread. Override the run() method with your task. Call start() to begin
execution (NOT run() directly — start() calls run() internally in a new thread).
class MyThread extends Thread { public void run()
{ [Link]("Running: " + [Link]().getId()); }}
MyThread t = new MyThread(); [Link](); // launches new thread
▶ Method 2: Implementing Runnable interface
• Create a class that implements Runnable. Override run(). Pass object to Thread constructor. Call
start().
class MyRun implements Runnable { public void run()
{ [Link]("Running"); }} Thread t = new Thread(new MyRun());
[Link]();
Which to prefer? Implement Runnable — because Java doesn't support multiple inheritance, and
implementing Runnable keeps your class free to extend another class.
🎯preferred
Likely Exam Q: Write programs creating threads using both methods. Why is Runnable
over extending Thread?
5.3 Thread Life Cycle
▶ Key Points
• New — thread created but start() not called yet.
• Runnable — start() called; thread is ready to run, waiting for CPU.
• Blocked — waiting for a monitor lock (to enter synchronized block).
Page 12 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
• Waiting — waiting indefinitely for another thread's notification (via wait()).
• Timed Waiting — waiting for specified time (via sleep(ms) or wait(ms)).
• Terminated — run() method finished executing normally, or exception occurred.
• Use [Link]() to get current state. [Link] is an enum with these 6 constants.
💡[Link]([Link]());
Example: Thread t = new Thread(() -> { ... }); [Link]([Link]()); // NEW [Link]();
// RUNNABLE
🎯moveLikely Exam Q: Draw and explain the life cycle of a thread in Java. What causes a thread to
to each state?
5.4 Inter-thread Communication (wait, notify, notifyAll)
▶ Core Idea
These three methods allow threads to cooperate. Instead of a thread constantly checking a
condition (wasting CPU), it calls wait() to release its lock and sleep until notified. The producing
thread then calls notify() when the condition is met.
▶ Key Points
• wait() — releases the lock on the object and puts the thread in Waiting state. Must be called from
synchronized context.
• notify() — wakes up one thread waiting on this object's monitor.
• notifyAll() — wakes up ALL threads waiting on this object's monitor.
• All three are methods of the Object class (not Thread class). This allows any object to act as a
lock.
• These must be called only from synchronized blocks/methods, otherwise
IllegalMonitorStateException is thrown.
• When a thread calls wait(), it releases that object's lock but keeps all other locks it holds.
▶ wait() vs sleep()
• wait() releases the lock; sleep() does NOT release the lock.
• wait() is from Object class; sleep() is from Thread class (static method).
• wait() must be notified by notify(); sleep() wakes up after specified time.
🎯is theLikely Exam Q: Explain inter-thread communication using wait(), notify(), and notifyAll(). What
difference between wait() and sleep()?
Page 13 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 06 — More on Multithreading
6.1 Suspending, Resuming, and Stopping Threads
▶ Key Points
• suspend() — moves thread from Running to Suspended state. Deprecated because it's
deadlock-prone.
• resume() — wakes a suspended thread. Only works with suspend(). Also deprecated.
• stop() — terminates thread immediately. Cannot be restarted. Also deprecated.
• Modern approach 1: Boolean flag — thread's run() checks a volatile boolean; set it to false to
stop.
• Modern approach 2: [Link]() — sets interrupted flag; thread checks
[Link]() to stop.
// Modern way to stop a thread class MyThread implements Runnable { private
boolean exit = false; public void run() { while(!exit) { /* do work
*/ } } public void stop() { exit = true; } }
🎯alternatives
Likely Exam Q: Why are suspend(), resume(), and stop() deprecated? Explain modern
to stop a thread.
6.2 Deadlock
▶ Core Idea
Deadlock happens when two threads are each waiting for a lock that the other holds — and neither
can proceed. It's like two cars stuck nose-to-nose on a narrow road, each waiting for the other to
reverse. Because synchronized keyword causes thread blocking, it's the usual culprit.
▶ Key Points
• Occurs when: Thread 1 holds Lock A, waits for Lock B. Thread 2 holds Lock B, waits for Lock A.
• Difficult to debug: occurs only when threads time-slice in specific order.
▶ Solutions to Deadlock
• Avoid Unnecessary Locks — only lock when truly needed.
• Avoid Nested Locks — don't acquire a second lock while holding one.
• Use [Link]() — ensures a thread finishes before another starts.
• Lock Ordering — always acquire locks in a consistent numeric order.
• Lock Timeout — try to acquire lock; if timeout reached, release and retry.
🎯 Likely Exam Q: Write a program to illustrate a deadlock situation. How would you resolve it?
Page 14 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 07 — Synchronization & Exception Handling
7.1 Thread Synchronization
▶ Core Idea
When multiple threads access shared data simultaneously, data gets corrupted. Synchronization
ensures only one thread at a time accesses a critical section. Java uses the synchronized keyword
and the monitor (lock) concept to do this.
▶ Key Points
• Synchronized method: declare method with synchronized. Only one thread can call this method
on an object at a time.
• Synchronized block: synchronized(object) { ... } — finer control; only the block is locked, not the
whole method.
• Every object has an associated monitor (lock). A thread 'enters' the monitor by acquiring the lock.
• If a thread owns a lock, other threads attempting to acquire the same lock are blocked.
• For static synchronized methods, the lock is on the Class object itself.
// Synchronized method public synchronized void printTable(int n) { for(int
i=1; i<=5; i++) [Link](n*i); } // Synchronized block
synchronized(this) { // only this block is protected }
🎯andLikely Exam Q: What is synchronization and why is it needed? Explain synchronized methods
synchronized blocks with code.
7.2 Exception Handling
▶ Core Idea
An exception is a runtime problem that disrupts normal execution. Java's exception handling
separates error-handling code from main logic, making programs more readable and robust. The
core idea is: try the risky code, catch the problem if it occurs, and always execute cleanup in finally.
▶ Types of Exceptions
• Checked Exceptions — checked at compile time. Must be declared with throws or caught.
Examples: IOException, SQLException, ClassNotFoundException.
• Unchecked Exceptions (RuntimeException) — occur at runtime. Examples: NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException.
• Error — serious problems not meant to be caught. Examples: OutOfMemoryError,
StackOverflowError.
▶ Exception Keywords
• try — wraps the risky code that might throw an exception.
• catch — catches and handles the thrown exception. Multiple catch blocks allowed.
• finally — always executes, whether exception occurred or not. Used for cleanup (closing files,
etc.).
• throw — manually throw an exception: throw new ArithmeticException("msg");
• throws — declare that a method might throw an exception: public void method() throws
IOException
Page 15 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
try { int result = 10 / 0; // throws ArithmeticException }
catch(ArithmeticException e) { [Link]("Can't divide by zero: "
+ [Link]()); } finally { [Link]("This always runs"); }
🎯example.
Likely Exam Q: What are checked vs unchecked exceptions? Explain try-catch-finally with an
When would you use throws vs throw?
7.3 Exception Handling in Multithreading
▶ Key Points
• A child thread's exceptions don't propagate to the parent thread automatically.
• Strategy 1: Use try-catch inside the run() method (not recommended as it can hide errors).
• Strategy 2: Implement [Link] — customize how uncaught
exceptions are handled.
• Set default handler: [Link](handler) — catches all
uncaught exceptions across threads.
class UCEH implements [Link] { public void
uncaughtException(Thread t, Throwable e) { [Link]("Caught: "
+ e); } } [Link](new UCEH()); throw new
Exception("test"); // caught by handler
🎯program
Likely Exam Q: How do you handle exceptions in a multithreaded environment? Write a
demonstrating UncaughtExceptionHandler.
Page 16 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 08 — Swings (GUI Programming)
8.1 Introduction to Swing
▶ Core Idea
Swing is Java's GUI library — it provides components like buttons, text boxes, tables, etc. It's in the
[Link] package. Compared to old AWT (Abstract Window Toolkit), Swing is more powerful,
elegant, and platform-independent. The key feature: pluggable look and feel — you can change
how the UI looks without changing logic.
▶ Key Points
• Part of Java Foundation Classes (JFC).
• All Swing components start with 'J': JButton, JFrame, JLabel, JTextField, JPanel, etc.
• Swing extends AWT components and is more flexible.
• JFrame is the main window. Add components to it using add() method.
• Must call setVisible(true) to display the window, setSize(w, h) to set dimensions.
🎯 Likely Exam Q: What is Swing? How is it different from AWT?
8.2 Key Swing Components
▶ JButton
• Creates clickable buttons. Constructors: JButton(), JButton(String text), JButton(Icon img),
JButton(String, Icon).
• Must implement ActionListener to handle button clicks.
JButton b = new JButton("Click Me"); [Link](new Dimension(100,
30)); [Link](b);
▶ JRadioButton
• Radio buttons for mutually exclusive choices. Group them with ButtonGroup so only one can be
selected at a time.
JRadioButton r1 = new JRadioButton("Option A"); JRadioButton r2 = new
JRadioButton("Option B"); ButtonGroup bg = new ButtonGroup(); [Link](r1);
[Link](r2);
▶ JTextArea
• Multi-line text input field. Constructors: JTextArea(), JTextArea(rows, cols), JTextArea(text).
• Use JScrollPane to add scrollbars: new JScrollPane(textArea).
▶ JComboBox
• Drop-down selection list. addItem(value) to add options. getSelectedItem() / getSelectedIndex()
to get choice.
▶ JTable
• Displays tabular data. Constructor: JTable(Object[][] data, Object[] columnNames).
• Add to JScrollPane for proper rendering with scrollbars and column headers.
🎯JRadioButton,
Likely Exam Q: Write a program to create a simple form with JButton, JTextField,
and JComboBox.
Page 17 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 09 — More on Swings (Layouts)
9.1 Layout Managers
▶ Core Idea
Layout managers control how components are arranged inside a container. Rather than hardcoding
pixel positions, you choose a layout strategy — and Java handles positioning automatically even if
the window is resized.
▶ Key Points
• FlowLayout — places components left to right, top to bottom (default for JPanel). Simple but not
flexible.
• BorderLayout — divides container into 5 regions: NORTH, SOUTH, EAST, WEST, CENTER.
Default for JFrame.
• GridLayout — arranges in a grid of rows and columns. All cells equal size.
• GridBagLayout — most flexible; allows spanning multiple rows/columns with fine control.
• CardLayout — stacks components like cards; shows one at a time. Good for wizard-style UI.
• BoxLayout — arranges components in a single row or column.
// BorderLayout example [Link](new BorderLayout()); [Link](new
JButton("Top"), [Link]); [Link](new JButton("Main"),
[Link]);
🎯layoutLikely Exam Q: Explain any three layout managers in Java with examples. What is the default
of JFrame?
Page 18 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 10 — More on Swings / Event Handling
10.1 Event Handling
▶ Core Idea
Event handling is how your GUI responds to user actions — like clicking a button or typing text.
Java uses the delegation model: a component (event source) generates an event, and a listener
(event handler) responds to it.
▶ Key Points
• Event Source — the component that generates the event (e.g., a JButton).
• Event Listener — interface that defines callback methods. Must be registered on the source.
• ActionListener — handles button clicks. Method: actionPerformed(ActionEvent e).
• MouseListener — handles mouse events: mouseClicked(), mousePressed(), mouseReleased(),
etc.
• KeyListener — handles keyboard events: keyPressed(), keyReleased(), keyTyped().
• WindowListener — handles window events: windowClosing(), windowOpened(), etc.
• Register: [Link](this) or [Link](new MyListener()).
JButton b = new JButton("Submit"); [Link](e ->
[Link]("Button clicked!")); // Lambda as ActionListener — clean
and concise
🎯a message
Likely Exam Q: Explain the event delegation model in Java Swing. Write a program that shows
when a button is clicked.
Page 19 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 11 — Managing Data using JDBC
11.1 JDBC Introduction
▶ Core Idea
JDBC (Java Database Connectivity) is the API that lets Java programs talk to relational databases
like MySQL, Oracle, or SQLite. It's a bridge between Java code and SQL. The core idea: load a
driver, connect to the database, send SQL queries, and process results.
▶ Key Points
• JDBC API is in [Link] and [Link] packages.
• JDBC drivers: Type 1 (JDBC-ODBC Bridge), Type 2 (Native API), Type 3 (Network Protocol),
Type 4 (Thin/Pure Java — most common today).
• Core interfaces: Driver, Connection, Statement, PreparedStatement, ResultSet,
CallableStatement.
🎯 Likely Exam Q: What is JDBC? Name the types of JDBC drivers and explain Type 4.
11.2 Steps to Connect to a Database
▶ Key Points
• Step 1: Register the driver — [Link]("[Link]");
• Step 2: Create connection — Connection con = [Link](url, user, pass);
• Step 3: Create statement — Statement stmt = [Link]();
• Step 4: Execute query — ResultSet rs = [Link]("SELECT * FROM table");
• Step 5: Process results — while([Link]()) { [Link]([Link]("name")); }
• Step 6: Close connection — [Link](); [Link](); [Link]();
[Link]("[Link]"); Connection con =
[Link]( "jdbc:mysql://localhost/mydb", "root",
"password"); Statement stmt = [Link](); ResultSet rs =
[Link]("SELECT * FROM students"); while([Link]())
{ [Link]([Link](1) + " " + [Link](2)); } [Link]();
11.3 Statement vs PreparedStatement
▶ Key Points
• Statement — used for simple, static SQL queries. Vulnerable to SQL injection.
• PreparedStatement — pre-compiled query with ? placeholders. Safer, faster for repeated
queries.
• PreparedStatement: [Link](1, 101); [Link](2, "Alice");
• CallableStatement — used to call stored procedures in the database.
• executeQuery() — for SELECT (returns ResultSet). executeUpdate() — for
INSERT/UPDATE/DELETE (returns row count). execute() — for any SQL.
PreparedStatement pstmt = [Link]( "INSERT INTO students
VALUES(?, ?)"); [Link](1, 101); [Link](2, "Alice");
[Link]();
Page 20 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
🎯WriteLikely Exam Q: Explain PreparedStatement vs Statement. Why is PreparedStatement safer?
a JDBC program to insert a record.
Page 21 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 12 — More on JDBC
12.1 ResultSet Types and Scrollability
▶ Key Points
• TYPE_FORWARD_ONLY (default) — can only move forward through results.
• TYPE_SCROLL_INSENSITIVE — can scroll in both directions; insensitive to changes made by
others.
• TYPE_SCROLL_SENSITIVE — can scroll in both directions; reflects changes made to the
database.
• CONCUR_READ_ONLY — ResultSet is read-only.
• CONCUR_UPDATABLE — ResultSet can be updated.
• Navigation methods: next(), previous(), first(), last(), absolute(n), relative(n), beforeFirst(),
afterLast().
🎯ResultSet?
Likely Exam Q: What are the different types of ResultSet? How do you create a scrollable
12.2 Transaction Management
▶ Key Points
• By default, JDBC auto-commits each SQL statement. Disable with [Link](false).
• [Link]() — saves all changes made since last commit.
• [Link]() — undoes all changes since last commit.
• Transactions ensure ACID properties: Atomicity, Consistency, Isolation, Durability.
• Always wrap transactions in try-catch; call rollback() in catch block.
[Link](false); try { [Link]("UPDATE acc SET bal =
bal - 500 WHERE id=1"); [Link]("UPDATE acc SET bal = bal + 500
WHERE id=2"); [Link](); // both succeed together } catch(Exception e) {
[Link](); // undo if anything fails }
🎯WriteLikely Exam Q: Explain transaction management in JDBC. What are the ACID properties?
a program demonstrating commit and rollback.
Page 22 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 13 — Network Programming
13.1 Networking Basics
▶ Core Idea
Java's networking capabilities allow programs to communicate over the internet using standard
protocols. The two main protocols are TCP (reliable, connection-oriented) and UDP (faster,
connectionless). Java wraps all of this neatly in the [Link] package.
▶ Key Points
• IP Address — unique identifier for a device on a network.
• Port Number — identifies a specific application on a device (0-65535). Well-known ports:
HTTP=80, FTP=21, SMTP=25.
• Socket — endpoint for communication. Combination of IP + Port.
• TCP — guaranteed delivery, ordered. Used for web, email, file transfer.
• UDP — no guarantee, faster. Used for video streaming, online gaming.
• InetAddress class — represents an IP address. [Link]("hostname") to resolve.
🎯 Likely Exam Q: What is a socket? Explain the difference between TCP and UDP networking.
13.2 Socket Programming (TCP)
▶ Key Points
• Server side: ServerSocket ss = new ServerSocket(port); Socket client = [Link](); — blocks
until client connects.
• Client side: Socket s = new Socket(serverIP, port); — connects to server.
• Communication: get InputStream/OutputStream from socket. Use BufferedReader for reading,
PrintWriter for writing.
• Always close sockets in finally block or use try-with-resources.
// SERVER ServerSocket ss = new ServerSocket(5000); Socket s =
[Link](); // waits for client BufferedReader br = new
BufferedReader( new InputStreamReader([Link]()));
[Link]("Client: " + [Link]()); // CLIENT Socket s = new
Socket("localhost", 5000); PrintWriter pw = new
PrintWriter([Link](), true); [Link]("Hello Server!");
🎯clientLikely Exam Q: Write a simple client-server program in Java using TCP sockets where the
sends a message to the server.
Page 23 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
Unit 14 — More on Network Programming
14.1 URL and URLConnection
▶ Key Points
• URL class — represents a Uniform Resource Locator. URL url = new URL("[Link]
• [Link]() — returns InputStream to read content from URL.
• URLConnection — provides more control: set request headers, read response headers.
• HttpURLConnection — HTTP-specific subclass. Set method: setRequestMethod("GET" or
"POST").
URL url = new URL("[Link] BufferedReader in = new
BufferedReader( new InputStreamReader([Link]())); String line;
while((line = [Link]()) != null) [Link](line); [Link]();
🎯fromLikely Exam Q: How do you fetch data from a URL in Java? Write a program to read content
a web page.
14.2 Datagram Sockets (UDP)
▶ Key Points
• DatagramSocket — for sending/receiving UDP packets.
• DatagramPacket — wraps data to be sent. Contains byte array, length, address, and port.
• Sending: DatagramSocket ds = new DatagramSocket(); [Link](packet);
• Receiving: DatagramSocket ds = new DatagramSocket(port); [Link](packet);
• UDP is connectionless — no need to establish a connection before sending. No guarantee of
delivery.
// SENDER (UDP) DatagramSocket ds = new DatagramSocket(); byte[] data =
"Hello UDP".getBytes(); InetAddress addr =
[Link]("localhost"); DatagramPacket dp = new
DatagramPacket(data, [Link], addr, 3000); [Link](dp); // RECEIVER
(UDP) DatagramSocket ds = new DatagramSocket(3000); byte[] buf = new
byte[1024]; DatagramPacket dp = new DatagramPacket(buf, [Link]);
[Link](dp); // blocks until packet arrives [Link](new
String([Link]()));
🎯andLikely Exam Q: Write a Java program to send and receive data using UDP (DatagramSocket
DatagramPacket). Compare TCP and UDP.
Page 24 of 25
ECAP615 — Programming in Java Exam Notes | Lovely Professional University
⚡ Quick Revision — Last-Minute Cheat Sheet
Common MCQ Traps to Remember
• Arrays start at index 0, not 1.
• String is immutable; StringBuffer is mutable and synchronized; StringBuilder is mutable and non-
synchronized.
• wait() and notify() are in Object class, NOT Thread class.
• wait() releases the lock; sleep() does NOT release the lock.
• Multiple inheritance is NOT supported with classes in Java — only with interfaces.
• Constructors are NOT inherited.
• TreeSet stores in ascending sorted order. ArrayList maintains insertion order.
• ArrayList uses indexed array internally; LinkedList uses doubly linked nodes.
• Comparable uses compareTo() from [Link]; Comparator uses compare() from [Link].
• JDK ⊃ JRE ⊃ JVM. JVM is platform-dependent; Java programs are platform-independent.
• Bytecode runs on JVM. Source code (.java) → bytecode (.class) via javac.
• checked exceptions are checked at compile-time; unchecked at runtime.
• synchronized keyword is used to avoid race conditions. It acquires a monitor lock.
• Deadlock is caused by nested synchronized blocks — avoid by consistent lock ordering.
• Lambda expressions work with functional interfaces (single abstract method).
• JDBC steps: Load driver → Get connection → Create statement → Execute → Process
ResultSet → Close.
• TCP uses ServerSocket (server) and Socket (client). UDP uses DatagramSocket and
DatagramPacket.
Good luck on your exam! You've got this. 💪
ECAP615 — Programming in Java | Lovely Professional University
Page 25 of 25