Learn Java Programming
Master Java from basics to advanced topics with concise lessons and practical examples. Follow a structured path inspired by reputable learning resources.
Reference guide: Programiz — Getting Started with Java [0]
Java Exception Handling
Exceptions represent unexpected conditions during program execution. Java's try/catch/finally mechanism lets you recover gracefully, provide meaningful error messages, and prevent crashes.
try / catch / finally
try {
int result = 10 / 0; // ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage()); // / by zero
} finally {
System.out.println("Always executes"); // cleanup
}
// Multiple catch blocks (most specific first)
try {
String[] arr = {"hello"};
int num = Integer.parseInt(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index error");
} catch (NumberFormatException e) {
System.out.println("Parse error");
} catch (Exception e) {
System.out.println("General: " + e.getMessage());
}
// Multi-catch (Java 7+)
try {
riskyMethod();
} catch (IOException | SQLException e) {
System.out.println("IO or DB error: " + e.getMessage());
}
Checked vs Unchecked Exceptions
| Type | Parent Class | Must Handle? | Examples |
|---|---|---|---|
| Checked | Exception | Yes (compile error) | IOException, SQLException, FileNotFoundException |
| Unchecked | RuntimeException | No (optional) | NullPointerException, IndexOutOfBounds, IllegalArgument |
| Error | Error | No (unrecoverable) | OutOfMemoryError, StackOverflowError |
import java.io.*;
// CHECKED: must declare with throws or handle with try/catch
public static String readFile(String path) throws IOException {
return new String(Files.readAllBytes(Path.of(path)));
}
// UNCHECKED: no requirement to declare/catch
public static int divide(int a, int b) {
if (b == 0) throw new IllegalArgumentException("Cannot divide by zero");
return a / b;
}
// Calling checked method — MUST handle
try {
String data = readFile("config.txt");
} catch (IOException e) {
System.out.println("File error: " + e.getMessage());
}
Try-with-Resources (Auto-closing)
import java.io.*;
// Resources in try() are auto-closed (must implement AutoCloseable)
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("out.txt"))) {
String line;
while ((line = br.readLine()) != null) {
pw.println(line.toUpperCase());
}
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
}
// br and pw are automatically closed here — even if exception occurs!
Try-with-resources (Java 7+) eliminates the need for manual close in finally blocks. It is the standard way to handle files, database connections, streams, and sockets.
Custom Exceptions
// Custom checked exception with additional context
class InsufficientFundsException extends Exception {
private final double shortfall;
public InsufficientFundsException(double shortfall) {
super("Insufficient funds. Short by: $" + String.format("%.2f", shortfall));
this.shortfall = shortfall;
}
public double getShortfall() { return shortfall; }
}
// Using in a class
class BankAccount {
private double balance;
public BankAccount(double balance) { this.balance = balance; }
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
}
// Handling
BankAccount acc = new BankAccount(100);
try {
acc.withdraw(150);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage()); // Insufficient funds. Short by: $50.00
System.out.println(e.getShortfall()); // 50.0
}
throw vs throws
// throw — creates and throws an exception object (inside method body)
public static void validateAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Invalid age: " + age);
}
}
// throws — declares that a method MAY throw (in method signature)
public static String loadConfig() throws IOException, FileNotFoundException {
return Files.readString(Path.of("config.properties"));
}
// Wrapping exceptions (preserve original cause)
public static void processData() {
try {
loadConfig();
} catch (IOException e) {
throw new RuntimeException("Config load failed", e); // wrap with cause
}
}
Key Takeaways
- Checked exceptions must be caught or declared; unchecked (RuntimeException) are optional.
- Use try-with-resources for anything implementing
AutoCloseable(files, connections, streams). - Never swallow exceptions with empty catch blocks — at minimum log the error.
- Create custom exceptions for domain-specific errors with meaningful messages and context fields.
- Catch the most specific exception first; catch-all
Exceptionshould be last. finallyalways executes — use for cleanup, but prefer try-with-resources for closeable resources.
Optional for expected "not found" scenarios, and reserve exceptions for truly exceptional conditions.Java Tutorial FAQs
How do I run Java online?
How do I install Java on Windows?
JAVA_HOME and update the Path variable to include the JDK bin directory. Verify with java --version. [0]How do I install Java on macOS?
export JAVA_HOME=$(/usr/libexec/java_home) and update PATH to include $JAVA_HOME/bin. Verify with java --version. [0]Do I need the JDK to compile Java?
javac) and tools needed to build Java applications. For quick tests, the online compiler is a convenient alternative.What is Java used for?
Learn Java the Practical Way
Whether you’re new to programming or expanding your skills, this Java tutorial focuses on hands-on learning. Each topic pairs clear explanations with short, working examples that you can run online. Move from fundamentals—variables, data types, and control flow—to core OOP concepts like classes, inheritance, and interfaces. Along the way, you’ll see idiomatic Java patterns and simple best practices that build confidence.
Why this guide? It’s designed for real-world use: fast to read, easy to try, and friendly on mobile. Bookmark it and return whenever you need a refresher or a quick example.
Java Programming Tutorial — Learn Java Step by Step
Java is one of the most widely-used programming languages in the world, powering Android apps, enterprise backends, cloud services, and scientific computing. This tutorial teaches Java from the ground up with practical, runnable examples you can try in our free Java Compiler or any local IDE.
Each topic includes multiple code examples with explanations, expected output, and best practices. Whether you are a complete beginner or refreshing your knowledge of a specific feature, every page gives you immediately usable code.
What This Tutorial Covers
- Basics: Hello World, variables, data types, operators
- Control Flow: if/else, switch, for, while, break/continue
- Methods: Parameters, return types, overloading, recursion
- Arrays & Strings: Declaration, manipulation, StringBuilder
- OOP: Classes, objects, constructors, encapsulation
- Inheritance: extends, super, abstract classes, final
- Interfaces: Abstraction, default methods, functional interfaces
- Collections: ArrayList, HashMap, HashSet, LinkedList
- Exceptions: try/catch/finally, custom exceptions
- Generics: Type parameters, bounded types, wildcards
- Streams (Java 8+): filter, map, reduce, collect
- File I/O: BufferedReader, Files API, serialisation
Why Learn Java in 2026?
- Enterprise dominance: Java powers most Fortune 500 backends via Spring Boot and Jakarta EE
- Android development: Java + Kotlin build apps for 3+ billion active Android devices
- Job market: Top 3 most-demanded language on LinkedIn, Indeed, and Stack Overflow survey
- Platform independence: Write once, run anywhere — bytecode runs on any JVM
- Modern evolution: Java 17/21 LTS added records, sealed classes, virtual threads, pattern matching
- Ecosystem: Maven/Gradle, IntelliJ IDEA, 100,000+ libraries, massive community
How to Get Started
- Run code online: Use our Java Compiler — no installation needed
- Install JDK locally: Download OpenJDK 17+ from adoptium.net
- Choose an IDE: IntelliJ IDEA Community (free), Eclipse, or VS Code with Java Extension Pack
- Follow topics in order: Start from Hello World and progress sequentially
- Build a project: After OOP, build a small CRUD app to solidify your knowledge
Frequently Asked Questions
No. This tutorial starts from absolute basics (Hello World, variables) and progresses to advanced topics. Each concept builds on the previous one.
Java 17 (LTS) is recommended. All examples in this tutorial work on Java 17+. Our online compiler uses the latest stable release.
Basics take 4–6 weeks of daily practice. Intermediate topics (collections, generics) add 4–6 more weeks. Job-readiness typically requires 3–6 months total.
Yes, completely free. No account, no sign-up. All topics and examples are available without any restriction.
Who Is This For?
Complete beginners choosing Java as their first language. CS students preparing for university courses and exams. Self-taught developers building a strong OOP foundation. Python/JS developers learning Java for backend or Android work. Interview candidates practising Java data structures. Professional developers needing a quick reference for specific Java features.