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

Methods in Java

Methods are reusable blocks of code that perform a specific task. They accept parameters, execute logic, and optionally return a value. Well-designed methods make code modular, testable, and easier to understand.

Basic Method with Parameters and Return

methods_basic.java
public class Calculator {

    // Method with parameters and return value
    public static int add(int a, int b) {
        return a + b;
    }

    // Method with no return value (void)
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Method with multiple return points
    public static String getGrade(int score) {
        if (score >= 90) return "A";
        if (score >= 80) return "B";
        if (score >= 70) return "C";
        if (score >= 60) return "D";
        return "F";
    }

    public static void main(String[] args) {
        int sum = add(5, 3);          // 8
        greet("Alice");                // Hello, Alice!
        String grade = getGrade(85);   // "B"
        System.out.println(sum + " " + grade);
    }
}

Every method has: an access modifier (public/private), an optional static keyword, a return type (or void), a name, and parameters in parentheses.

Method Overloading

overloading.java
public class MathUtils {

    // Same method name, different parameter lists
    public static int multiply(int a, int b) {
        return a * b;
    }

    public static double multiply(double a, double b) {
        return a * b;
    }

    public static int multiply(int a, int b, int c) {
        return a * b * c;
    }

    public static void main(String[] args) {
        System.out.println(multiply(3, 4));       // 12 (int version)
        System.out.println(multiply(2.5, 3.0));   // 7.5 (double version)
        System.out.println(multiply(2, 3, 4));    // 24 (three-param version)
    }
}

Overloading lets you define multiple methods with the same name but different parameter types or counts. Java picks the correct version at compile time based on the arguments you pass.

Varargs (Variable Arguments)

varargs.java
public class VarargsDemo {

    // Accepts any number of int arguments
    public static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) {
            total += n;
        }
        return total;
    }

    // Varargs must be the LAST parameter
    public static String format(String prefix, String... items) {
        return prefix + ": " + String.join(", ", items);
    }

    public static void main(String[] args) {
        System.out.println(sum(1, 2, 3));         // 6
        System.out.println(sum(10, 20, 30, 40));  // 100
        System.out.println(sum());                 // 0 (empty is valid)

        System.out.println(format("Fruits", "Apple", "Banana", "Cherry"));
        // Fruits: Apple, Banana, Cherry
    }
}

Varargs (int... numbers) accepts zero or more arguments as an array internally. It must be the last parameter. Useful for utility methods like sum(), printf(), and logging.

Static vs Instance Methods

static_vs_instance.java
public class BankAccount {
    private String owner;
    private double balance;
    private static int totalAccounts = 0;  // shared across all instances

    public BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        this.balance = initialBalance;
        totalAccounts++;
    }

    // Instance method — operates on THIS object's data
    public void deposit(double amount) {
        if (amount > 0) {
            this.balance += amount;
        }
    }

    // Instance method with return value
    public double getBalance() {
        return this.balance;
    }

    // Static method — belongs to the CLASS, not any specific object
    public static int getTotalAccounts() {
        return totalAccounts;
    }

    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount("Alice", 1000);
        BankAccount acc2 = new BankAccount("Bob", 500);

        acc1.deposit(200);  // instance method on acc1
        System.out.println(acc1.getBalance());  // 1200.0

        // Static method called on the class
        System.out.println(BankAccount.getTotalAccounts());  // 2
    }
}
  • Instance methods have access to this and can read/modify the object's fields.
  • Static methods belong to the class itself and cannot access instance fields (no this).
  • Use static for utility/helper methods that don't depend on object state.

Recursion

recursion.java
public class Recursion {

    // Recursive factorial: n! = n * (n-1)!
    public static long factorial(int n) {
        if (n <= 1) return 1;       // base case
        return n * factorial(n - 1); // recursive call
    }

    // Recursive Fibonacci
    public static int fibonacci(int n) {
        if (n <= 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String[] args) {
        System.out.println(factorial(5));   // 120
        System.out.println(fibonacci(10));  // 55
    }
}

Every recursive method needs a base case (stops recursion) and a recursive case (calls itself with a smaller problem). Without a base case, you get a StackOverflowError.

Key Takeaways

  • Methods should do one thing well — if a method does too much, split it into smaller methods.
  • Java passes arguments by value — primitives are copied; object references are copied (not the objects).
  • Use overloading to provide multiple versions with different parameter types.
  • Use varargs (Type...) for flexible argument counts; it must be the last parameter.
  • Use static for utility methods that don't need object state; use instance methods for behavior tied to an object.
  • Every recursive method needs a clear base case to prevent infinite recursion.
Best Practice: Give methods descriptive verb-based names (calculateTotal, validateEmail, getUserById). Keep methods short (under 20 lines ideally). If you can't name a method clearly, it probably does too many things.

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.