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]

Tutorial Contents

Java Interfaces

Interfaces define contracts that classes must implement. They enable polymorphism without inheritance, allow multiple implementation, and are the foundation of Java's functional programming features (lambdas).

Basic Interface and Implementation

interfaces.java
// Interface defines WHAT, not HOW
interface Payable {
    double calculatePay();       // abstract method
    String getPaymentMethod();   // abstract method
}

interface Taxable {
    double calculateTax();
    default double getNetPay(double gross) {  // default method (Java 8+)
        return gross - calculateTax();
    }
}

// A class can implement MULTIPLE interfaces
class Employee implements Payable, Taxable {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    @Override
    public double calculatePay() { return salary; }

    @Override
    public String getPaymentMethod() { return "Direct Deposit"; }

    @Override
    public double calculateTax() { return salary * 0.30; }
}

// Type against the interface for flexibility
Payable emp = new Employee("Alice", 5000);
System.out.println(emp.calculatePay());  // 5000.0

Default and Static Methods (Java 8+)

default_methods.java
interface Logger {
    void log(String message);  // abstract — must implement

    // Default method — provides shared implementation
    default void info(String msg) { log("[INFO] " + msg); }
    default void warn(String msg) { log("[WARN] " + msg); }
    default void error(String msg) { log("[ERROR] " + msg); }

    // Static method — called on the interface itself
    static Logger consoleLogger() {
        return msg -> System.out.println(msg);  // lambda!
    }
}

class FileLogger implements Logger {
    @Override
    public void log(String message) {
        // Write to file...
        System.out.println("FILE: " + message);
    }
    // info(), warn(), error() are inherited from default methods
}

Logger logger = Logger.consoleLogger();  // static factory
logger.info("Application started");     // [INFO] Application started

Logger fileLogger = new FileLogger();
fileLogger.error("Disk full");          // FILE: [ERROR] Disk full

Functional Interfaces and Lambdas

functional.java
import java.util.*;
import java.util.function.*;

// Functional interface = exactly ONE abstract method
@FunctionalInterface
interface Transformer<T> {
    T transform(T input);
}

// Use with lambda expressions
Transformer<String> shout = s -> s.toUpperCase() + "!";
System.out.println(shout.transform("hello"));  // HELLO!

// Built-in functional interfaces
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String, Integer> toLength = String::length;
Consumer<String> printer = System.out::println;
Supplier<Double> random = Math::random;

// Using with collections
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
    .filter(n -> n.length() > 3)       // Predicate
    .map(String::toUpperCase)            // Function
    .forEach(System.out::println);       // Consumer
// ALICE, CHARLIE

Sealed Interfaces (Java 17+)

sealed.java
// Sealed interface restricts which classes can implement it
sealed interface Shape permits Circle, Square, Triangle {}

record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}

// Exhaustive pattern matching (Java 21+)
double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.radius() * c.radius();
        case Square s -> s.side() * s.side();
        case Triangle t -> 0.5 * t.base() * t.height();
        // No default needed — compiler verifies all cases!
    };
}

Key Takeaways

  • Interfaces define contracts; classes can implement multiple interfaces (unlike single inheritance).
  • default methods provide shared logic without breaking existing implementors.
  • Functional interfaces (one abstract method) enable lambdas and method references.
  • Program to interfaces, not implementations — this decouples your code and improves testability.
  • Sealed interfaces (Java 17+) create closed hierarchies that enable exhaustive pattern matching.
Best Practice: Keep interfaces small and focused (Interface Segregation Principle). A class should never be forced to implement methods it doesn't need. Prefer multiple small interfaces over one large one.

Java Tutorial FAQs

How do I run Java online?
Use the Java Online Compiler to write and execute Java directly in your browser—no setup needed. Click "Try Java Online" above to get started.
How do I install Java on Windows?
Download the JDK installer, run it, then set 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?
Install the appropriate JDK DMG (x64 or ARM64). In your shell profile, set 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?
Yes. The JDK provides the compiler (javac) and tools needed to build Java applications. For quick tests, the online compiler is a convenient alternative.
What is Java used for?
Java powers cross-platform applications including web services, Android apps, enterprise systems, and tooling built on the JVM. Its strong OOP model and rich libraries make it versatile.

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

  1. Run code online: Use our Java Compiler — no installation needed
  2. Install JDK locally: Download OpenJDK 17+ from adoptium.net
  3. Choose an IDE: IntelliJ IDEA Community (free), Eclipse, or VS Code with Java Extension Pack
  4. Follow topics in order: Start from Hello World and progress sequentially
  5. Build a project: After OOP, build a small CRUD app to solidify your knowledge

Frequently Asked Questions

Do I need prior programming experience?

No. This tutorial starts from absolute basics (Hello World, variables) and progresses to advanced topics. Each concept builds on the previous one.

Which Java version should I use?

Java 17 (LTS) is recommended. All examples in this tutorial work on Java 17+. Our online compiler uses the latest stable release.

How long does it take to learn Java?

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.

Is this tutorial free?

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.