Download Complete guide to Java programming notes 2 and more Study notes Java Programming in PDF only on Docsity!
☕ THE ULTIMATE COMPLETE JAVA
PROGRAMMING STUDY GUIDE
Units 1–8: From Hello World to Advanced GUI — The
Encyclopedia Edition
How to use this document: This is not a summary — it's a complete
course. Read it top-to-bottom once. Every concept has multiple
analogies, definitions, line-by-line code explanations, step-by-step
walkthroughs, common mistakes, real-world connections, and "why
it matters" notes. If a concept feels hard, re-read the analogy. Every line
of code is explained. Every keyword is defined. Nothing is assumed. This is
the only document you need.
A promise: By the end, you will understand Java from the ground up. You'll
know what every keyword does, why it exists, when to use it, and how to
combine everything into real applications.
📋 TABLE OF CONTENTS
1. PART 0: Java Fundamentals Refresher (What You Need Before Unit 1)
2. PART 1: Unit 1 — Exceptions and Strings
3. PART 2: Unit 2 — Packages and Accessibility
4. PART 3: Unit 3 — Multithreading
5. PART 4: Unit 4 — I/O Streams and Applets
6. PART 5: Unit 5 — JDBC and Database Programming
7. PART 6: Unit 6 — Generics and Collections
8. PART 7: Unit 7 — Files and Networking
9. PART 8: Unit 8 — GUI Programming
10. PART 9: Ten Complete Projects (Beginner → Advanced)
11. PART 10: Study Tips, Exam Strategies, and Final Cheat Sheets
📋 PART 0 — JAVA FUNDAMENTALS REFRESHER
Before we dive into Units 1–8, let's make sure you understand the foundation. If you
already know this, skim it. If not, read every word.
0.1 What Is Java?
Java is a high-level, object-oriented, platform-independent programming language
created by James Gosling at Sun Microsystems in 1995.
"Write once, run anywhere" (WORA): Java code compiles to bytecode , which runs
on the Java Virtual Machine (JVM). This means the same .class file runs on
Windows, Mac, and Linux.
Analogy: Java is like a USB cable. The same cable works with any device that has a
USB port. Similarly, Java bytecode works on any device with a JVM.
0.2 How Java Code Runs
text YourCode.java → javac (compiler) → YourCode.class (bytecode) → JVM → Runs on any OS
Step by step:
1. You write YourCode.java (human-readable). B
2. javac compiles it to YourCode.class (bytecode — not machine code).
3. The JVM interprets/compiles the bytecode to machine code for the specific OS.
4. Program runs.
Why this matters: You don't need to recompile for each OS. One .class file works
everywhere.
0.3 The Three Pillars of Java
Pillar Meaning Example
JVM Java Virtual Machine —
runs bytecode
The engine
JRE Java Runtime
Environment — JVM +
libraries
Engine + fuel
JDK Java Development Kit
— JRE + tools (javac,
javadoc)
Engine + fuel + mecha
nic tools
Analogy:
- JVM = car engine.
- JRE = car with engine and fuel (can drive, can't repair).
- JDK = car + engine + fuel + mechanic's toolbox (can drive AND build/repair).
0.4 Your First Java Program — Explained Line by Line
java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Line 1: public class HelloWorld {
- public — access modifier: this class is visible to everyone.
- class — keyword: defines a class (blueprint for objects).
- HelloWorld — the class name (must match the filename HelloWorld.java).
- { — opens the class body.
Line 2: public static void main(String[] args) {
- public — visible to everyone (the JVM must access it).
- static — belongs to the class, not an instance (so JVM can call without creating
an object).
// Arithmetic int sum = a + b; // 13 int diff = a - b; // 7 int product = a * b; // 30 int quotient = a / b; // 3 (integer division!) int remainder = a % b; // 1 // Comparison boolean eq = a == b; // false boolean ne = a != b; // true boolean gt = a > b; // true boolean lt = a < b; // false // Logical boolean and = (a > 5 ) && (b < 5 ); // true boolean or = (a > 15 ) || (b < 5 ); // true boolean not = !(a > 5 ); // false // Assignment a += 5 ; // a = a + 5 a -= 3 ; // a = a - 3 a *= 2 ; // a = a * 2 a /= 4 ; // a = a / 4 // Increment/Decrement a++; // a = a + 1 a--; // a = a – 1
Integer division warning: 10 / 3 = 3 , not 3.333. To get decimal, use 10.0 / 3.
0.7 Control Flow
if-else:
java if (age >= 18 ) { System.out.println("Adult"); } else if (age >= 13 ) { System.out.println("Teenager"); } else { System.out.println("Child"); }
switch:
java switch (day) { case 1 : System.out.println("Monday"); break; case 2 : System.out.println("Tuesday"); break; default: System.out.println("Other"); }
for loop:
java for (int i = 0 ; i < 5 ; i++) { System.out.println(i); }
while loop:
java int i = 0 ; while (i < 5 ) { System.out.println(i); i++; }
do-while loop:
java int i = 0 ; do { System.out.println(i); i++; } while (i < 5 );
for-each loop:
java int[] numbers = { 1 , 2 , 3 , 4 , 5 }; for (int num : numbers) { System.out.println(num); }
0.8 Methods
A method is a reusable block of code.
java public static int add(int a, int b) { return a + b; } // Usage int result = add( 5 , 3 ); // 8
Anatomy:
- public — access modifier.
- static — belongs to class, not instance.
- int — return type.
- add — method name.
- (int a, int b) — parameters.
- return a + b; — returns the result.
0.9 Classes and Objects
A class is a blueprint. An object is an instance of a class.
java public class Person { // Fields (attributes) private String name;
java public interface Flyable { void fly(); } public class Bird implements Flyable { @Override public void fly() { System.out.println("Flying!"); } }
implementsmeans "promises to provide these methods."
0.12 Polymorphism
Same method name, different behavior.
java Animal a = new Dog(); a.eat(); // Calls Dog's eat() if overridden, else Animal's
@Overrideensures you're actually overriding.
0.13 Arrays
java int[] numbers = new int[ 5 ]; // Array of 5 ints int[] nums = { 1 , 2 , 3 , 4 , 5 }; // Array with values String[] names = {"Ali", "Sara"}; System.out.println(nums[ 0 ]); // 1 System.out.println(nums.length); // 5
0.14 The String Class Basics
java String s = "Hello"; System.out.println(s.length()); // 5 System.out.println(s.charAt( 0 )); // H System.out.println(s.toUpperCase()); // HELLO
Now you're ready for Unit 1. Everything from here builds on this foundation.
⚠️ PART 1 — UNIT 1: EXCEPTIONS AND STRINGS
Chapter 1: Introduction to Exceptions
1.1 What Is an Exception?
An exception is an event that occurs during the execution of a program that disrupts
the normal flow of instructions. It's Java's way of saying: "Something went wrong,
and I can't continue normally."
Real-world analogy #1: You're driving to work. Your plan: leave home → take the
highway → arrive at the office. But there's a traffic jam. Your normal route is blocked.
You have two choices:
1. Handle it: Take a detour (catch the exception and continue).
2. Give up: Turn around and go home (let the exception propagate and crash).
Real-world analogy #2: You're withdrawing money from an ATM. You enter $100.
The ATM checks your balance. If insufficient, it shows "Insufficient funds" — that's an
exception being handled gracefully.
Real-world analogy #3: A restaurant order system. Customer orders a dish. The
kitchen realizes they're out of an ingredient. Options:
- Apologize and suggest alternatives (handle the exception).
- Crash the entire system (let it propagate).
Why exceptions matter:
- Stability: Without exception handling, one error crashes the entire program.
- Reliability: Users expect apps to handle errors gracefully.
- Debugging: Exceptions provide detailed information about what went wrong and
where.
- Separation of concerns: Error-handling code is separated from normal logic.
- Recovery: Programs can recover from errors and continue. 1.2 The Exception Hierarchy — Full Detail
Java's exception hierarchy is a tree. Understanding it is crucial for everything that
follows.
text Object │ Throwable / Error Exception / \ / OutOfMemory StackOverflow Checked RuntimeException │ │ ┌───────────┼─────┐ ├── NullPointerExcepti on │ │ │ ├── ArrayIndexOutOfBou nds IOException SQLException ├── ArithmeticException │ ├── NumberFormatException FileNotFoundException ├── ClassCastException │ └── IllegalArgumentExcept ion EOFException
Every class in this tree has a parent. For example:
- NullPointerException IS-A RuntimeException IS-A Exception IS-A Throwable IS-A
Object.
This matters because:
- Catching Exception catches both checked AND unchecked.
- Catching RuntimeException catches only unchecked.
- Catching Throwable catches everything including Error (usually a bad idea).
Feature Checked Exception Unchecked Exceptio
n
Parent class Exception (but NOT Run
timeException)
RuntimeException
When checked Compile time Runtime
Must handle? Yes — compiler forces y
ou
No — optional
Examples IOException, SQLExcepti
on, ClassNotFoundExcept
ion
NullPointerException, A
rithmeticException, Arr
ayIndexOutOfBoundsExcep tion
Purpose Recoverable conditions Programming bugs
Should you catch? Yes, if you can recover Rarely — fix the bug
instead
Analogy Weather forecast:
"Bring an umbrella"
You walked into a wall
Checked exception example — MUST handle:
java public void readFile() { FileReader reader = new FileReader("data.txt"); // ⚠ Compile error! }
Error message: Unreported exception java.io.FileNotFoundException; must be caught
or declared to be thrown
Fix 1: Handle it with try-catch
java public void readFile() { try { FileReader reader = new FileReader("data.txt"); // Use reader reader.close(); } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("IO error: " + e.getMessage()); } }
Line-by-line:
- try { — Everything inside might throw.
- new FileReader("data.txt") — Can throw FileNotFoundException (a checked
exception).
- catch (FileNotFoundException e) — Handle file-not-found specifically.
- catch (IOException e) — Handle other I/O errors.
Fix 2: Declare it with throws
java
public void readFile() throws IOException { FileReader reader = new FileReader("data.txt"); reader.close(); }
Now callers must handle it.
Unchecked exception example — optional to handle:
java public void divide() { int result = 10 / 0 ; // ⚠ ArithmeticException at runtime }
This compiles fine. The error only happens at runtime. You can catch it, but the
compiler doesn't force you.
java public void divide() { try { int result = 10 / 0 ; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } } 1.5 Why the Checked/Unchecked Distinction?
The philosophy:
- Checked exceptions are for predictable problems that a reasonable program
should recover from (file not found, network down).
- Unchecked exceptions are for programming bugs (null reference, bad index)
that should be fixed, not caught.
Analogy:
- Checked: "The road might be icy — the weather service warns you. Pack chains."
- Unchecked: "You drove off a cliff. That's your fault, not the weather's."
Common checked exceptions:
- IOException — I/O operations fail.
- SQLException — Database operations fail.
- ClassNotFoundException — Class not found at runtime.
- InterruptedException — Thread interrupted.
- FileNotFoundException — File doesn't exist.
Common unchecked exceptions:
- NullPointerException — Calling method on null.
- ArrayIndexOutOfBoundsException — Bad array index.
- ArithmeticException — Divide by zero.
- NumberFormatException — Parsing bad number.
- ClassCastException — Bad cast.
- IllegalArgumentException — Bad method argument. 1.6 Error vs Exception — Don't Confuse Them
2.2 Multiple catch Blocks — Handling Different Types java try { String str = null; System.out.println(str.length()); // Line A: NPE int[] arr = new int[ 5 ]; arr[ 10 ] = 100 ; // Line B: AIOOBE int result = 10 / 0 ; // Line C: AE } catch (NullPointerException e) { System.out.println("Null pointer! " + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Index out of bounds! " + e.getMessage()); } catch (ArithmeticException e) { System.out.println("Math error! " + e.getMessage()); } catch (Exception e) { System.out.println("Some other exception: " + e.getMessage()); }
Rules:
1. More specific exceptions must come BEFORE more general ones. If you
put catch (Exception e) first, the compiler will complain "exception has already
been caught" for the others.
2. Only the first matching catch runs. Others are skipped.
3. catch (Exception e) should be last (catches everything not caught above).
Line-by-line:
- Line A: str.length() — str is null, so calling .length() throws
NullPointerException. Caught by first catch.
- Line B: Would throw ArrayIndexOutOfBoundsException, but since Line A already
threw an exception, execution jumped to the catch block. Lines B and C never ex
ecute.
Key insight: Only one exception is thrown per try execution. Once an exception
occurs, the rest of try is skipped.
2.3 Multi-catch (Java 7+) — Cleaner Code java try { // risky code } catch (IOException | SQLException e) { System.out.println("Database or file error: " + e.getMessage()); logger.error("Error", e); }
Why: Reduces code duplication when the handling is the same for multiple exception
types.
Rules:
- e is effectively final — you can't reassign it.
- The types can't be related (no catching IOException | FileNotFoundException since
one extends the other).
- Useful for logging, re-throwing, or generic recovery. 2.4 The finally Block — Always Runs
Code in finally always executes, whether an exception occurred or not.
java FileReader reader = null; try { reader = new FileReader("data.txt"); // Read the file int data = reader.read(); } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println("Error closing file"); } } }
When does finally run?
1. After try completes normally.
2. After a catch runs.
3. Even if try has a return, break, or continue.
4. Even if an uncaught exception is propagating.
5. Even if try throws an exception not caught locally.
When does finally NOT run?
1. If JVM exits (System.exit()).
2. If the JVM crashes.
3. If the thread is killed.
Analogy: finally is like "whether the mission succeeds or fails, clean up your
equipment."
Common uses:
- Closing files, database connections, network sockets.
- Releasing locks.
- Logging.
- Cleanup code. 2.5 try-with-resources (Java 7+) — The Modern Way
Automatically closes resources that implement AutoCloseable or Closeable.
java try (FileReader reader = new FileReader("data.txt"); BufferedReader br = new BufferedReader(reader)) { String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { System.out.println("Error: " + e.getMessage()); }
Line-by-line:
// code that might throw IOException FileReader reader = new FileReader("data.txt"); }
throws keyword:
- Declares that a method might throw exceptions.
- Callers must handle or declare them.
- Can declare multiple: throws IOException, SQLException
- Comma-separated.
throw vs throws :
Keyword Purpose Where used Example
throw Actually throws
an exception
Inside method b
ody
throw new IOExce ption();
throws Declares that a
method might
throw
In method signat
ure
void read() thro ws IOException
Analogy:
- throws is like a warning label ("This method might throw IOException — caller
beware").
- throw is the actual act of throwing. 2.8 Creating Your Own Exceptions
You can create custom exception classes.
Custom checked exception:
java public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { super("Insufficient funds: need " + amount + " more"); this.amount = amount; } public double getAmount() { return amount; } }
Line-by-line:
- public class InsufficientFundsException extends Exception — Extends Exception,
so it's checked.
- private double amount; — Store extra info.
- public InsufficientFundsException(double amount) — Constructor takes the
missing amount.
- super("...") — Calls parent constructor with message.
- this.amount = amount; — Save the amount.
- getAmount() — Getter.
Custom unchecked exception:
java public class InvalidAgeException extends RuntimeException { public InvalidAgeException(String message) { super(message); } }
Extends RuntimeException — no need to declare or catch.
Usage:
java public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount - balance); } balance -= amount; } // Caller try { account.withdraw( 1000 ); } catch (InsufficientFundsException e) { System.out.println("Missing: " + e.getAmount()); }
When to create custom exceptions:
1. When built-in exceptions don't describe your error well.
2. When you need to attach extra data.
3. When you want to distinguish your errors from others.
4. When you want to force callers to handle specific errors.
2.9 Exception Chaining — Preserving the Cause java try { // Read config file } catch (IOException e) { throw new RuntimeException("Failed to load config", e); // ↑ Cause }
Line-by-line:
- catch (IOException e) — Caught the original.
- throw new RuntimeException("...", e) — Wrap it with context. e is the cause.
Why: The caller sees a meaningful exception, but the original cause isn't lost.
getCause() retrieves it.
2.10 The try-catch-finally Order java try { // 1. Try body } catch (SpecificException e) { // 2. Catch specific
try { riskyOperation(); } catch (SpecificException e) { logger.error("Operation failed", e); // Take recovery action } // ❌ BAD: Catching too broadly try { int x = Integer.parseInt("abc"); } catch (Exception e) { // Catches everything // ... } // ❌ GOOD: Catch specific try { int x = Integer.parseInt("abc"); } catch (NumberFormatException e) { // ... }
Chapter 3: Java's Exception Hierarchy in Detail
3.1 The Full Hierarchy — Every Common Exception text java.lang.Object └── java.lang.Throwable ├── java.lang.Error │ ├── OutOfMemoryError │ ├── StackOverflowError │ ├── VirtualMachineError │ ├── AssertionError │ └── LinkageError └── java.lang.Exception ├── Checked Exceptions │ ├── IOException │ │ ├── FileNotFoundException │ │ ├── EOFException │ │ └── InterruptedIOException │ ├── SQLException │ ├── ClassNotFoundException │ ├── InterruptedException │ ├── CloneNotSupportedException │ ├── ReflectiveOperationException │ └── ParseException └── RuntimeException (Unchecked) ├── NullPointerException ├── ArrayIndexOutOfBoundsException ├── ArithmeticException ├── NumberFormatException ├── ClassCastException ├── IllegalArgumentException ├── IllegalStateException ├── UnsupportedOperationException ├── IndexOutOfBoundsException ├── NegativeArraySizeException └── ConcurrentModificationException 3.2 Common Exceptions — Causes and Fixes
Exception Cause How to avoid
NullPointerException Calling method/field on
null
Check for null, use
Objects.requireNonNull ArrayIndexOutOfBoundsEx ception
Index >= length or < 0 Check bounds before a
ccess
ArithmeticException Divide by zero Check divisor
NumberFormatException Parse invalid string Validate input, use try-
catch
ClassCastException Bad cast Use instanceof before c
asting
IllegalArgumentExceptio n
Bad method argument Validate parameters at
start
FileNotFoundException File doesn't exist Check file.exists()
IOException General I/O failure Handle gracefully, retr
y
SQLException Database error Log, check connection,
retry
InterruptedException Thread interrupted Restore interrupt flag
ConcurrentModificationE xception
Modify collection while
iterating
Use iterator's remove
3.3 Stack Traces — Reading Them Like a Pro
When an exception is thrown, Java prints a stack trace.
text Exception in thread "main" java.lang.ArithmeticException: / by zero at com.example.Calculator.divide(Calculator.java:15) at com.example.Main.main(Main.java:8)
Reading a stack trace:
1. First line: Exception type + message.
2. Subsequent lines: Method calls, from innermost (where exception occurred) to
outermost (where program started).
3. Calculator.divide at line 15 — This is where the exception was thrown.
4. Main.main at line 8 — This is where divide() was called.
5. Read from bottom-up to trace how the program got there.
Analogy: A stack trace is like a receipt — it shows every step that led to the problem.
With chained exceptions:
text Exception in thread "main" java.lang.RuntimeException: Failed to load config at Main.main(Main.java:10) Caused by: java.io.FileNotFoundException: config.properties (No such file)