Programming language · Beginner to advanced

Learn Java step by step

Start with your first Java program, then learn variables, methods, classes, collections, error handling and testing through practical code examples. Every module explains the idea in plain language, walks through a code example and gives you a small task to try yourself.

Version snapshot: Java 27 · JDK 27. Java 27 is the latest feature release as of 21 October 2026. Java 25 is the current LTS release; choose the LTS line when your project prioritizes long support and stable tooling.

Before you begin

No prior programming experience is required. Install a JDK, which includes the compiler and tools needed to run Java programs.

What you’ll be able to do

Write structured Java programs, understand the runtime, use standard library collections, and test small applications.

Work through the modules in order if you’re new to Java. If you already know the basics, use the contents list to jump to a topic. Try each example by changing one value, running it again and explaining the result in your own words.

Java terms in simple language

JDK
The tools developers install to write, compile and run Java programs.
JVM
The Java Virtual Machine that runs compiled Java bytecode on a computer.
Class and object
A class describes a kind of thing; an object is one actual instance created from that description.
Collection
A standard Java structure for holding groups of values, such as a list of lessons.
Bytecode
The compiled instructions that the Java Virtual Machine reads and runs.
Constructor
A special part of a class that sets up a new object with its starting values.
Interface
A description of actions a class promises to provide, without prescribing every detail.
Generic type
A way to say what kind of value a collection or class should hold, so mistakes are caught earlier.
Exception
A signal that an operation failed, which code can catch and handle or pass to its caller.
Concurrency
Handling more than one task during the same period, for example while waiting for files or network work.
In this guide · 12 modules
  1. Key terms in simple language
  2. JDK, compiler, JVM and first program
  3. Variables, primitive types and expressions
  4. Conditions, switch and loops
  5. Methods, parameters and return values
  6. Arrays, strings and basic algorithms
  7. Classes, objects, constructors and encapsulation
  8. Interfaces, inheritance and composition
  9. Collections and choosing the right data structure
  10. Generics, enums and records
  11. Exceptions, validation and resource safety
  12. Lambdas, streams and Optional
  13. Packages, testing, concurrency and next steps
  14. Final project
  15. Official references
MODULE 01 / 12 · CONCEPT EXPLAINED

JDK, compiler, JVM and first program

The JDK is the toolkit you install to build Java programs. It includes javac, the compiler that turns your source code into bytecode. The JVM, or Java Virtual Machine, reads that bytecode and runs it on your computer. This separation is why compiled Java can run on different systems with a compatible JVM. Save the public class in a file with the same name, then run its main method to start the program.

Follow this example
class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java");
    }
}

// Save as Main.java, then run: java Main.java
Try it yourself: Compile and run a program that prints your name and calculates 7 * 8.
MODULE 02 / 12 · CONCEPT EXPLAINED

Variables, primitive types and expressions

Java asks you to tell it what kind of value each variable will hold, and the compiler checks that choice before the program runs. int stores whole numbers, double stores decimal numbers, boolean stores true or false, and String stores text. A variable with a clear name, such as lessons, is easier to read later. Watch out for integer division: 5 / 2 gives 2 because both values are whole numbers, so use a decimal type when you need 2.5.

Follow this example
int lessons = 4;
double score = 87.5;
boolean passed = score >= 40;
String learner = "Asha";
System.out.println(learner + ": " + lessons + ", passed=" + passed);
Try it yourself: Calculate a bill total using a decimal amount and tax rate; print the result with a clear label.
MODULE 03 / 12 · CONCEPT EXPLAINED

Conditions, switch and loops

A condition lets the program make a decision. if and else handle a yes-or-no choice, while switch is often easier to read when there are several named choices. Loops repeat work: for is useful when going through a range or list, and while repeats until a condition changes. Always check that a while loop can finish; otherwise the program may keep running forever.

Follow this example
int score = 72;
String result = score >= 60 ? "Pass" : "Retry";
for (int number = 1; number <= 5; number++) {
    System.out.println(number + " → " + result);
}
Try it yourself: Print a multiplication table with a loop and label each result.
MODULE 04 / 12 · CONCEPT EXPLAINED

Methods, parameters and return values

A method is a named set of instructions that does one job, such as calculating tax. Parameters are the input values you give the method; the return value is the answer it gives back. Separating calculation from printing makes a method easier to reuse in a menu, a web page or a test. Keep each method focused, and give its inputs and result types clear names so its purpose is easy to see.

Follow this example
static double withTax(double subtotal, double rate) {
    return subtotal * (1 + rate);
}

public static void main(String[] args) {
    System.out.println(withTax(100.0, 0.18));
}
Try it yourself: Write methods for the area of a rectangle and for checking whether an integer is even.
MODULE 05 / 12 · CONCEPT EXPLAINED

Arrays, strings and basic algorithms

Arrays have a fixed length and store values of one type. String objects are immutable, so operations produce new strings. Use StringBuilder when repeatedly assembling text in a loop. Learn to trace an algorithm with a small input before optimizing it.

Follow this example
int[] scores = {72, 91, 84};
int total = 0;
for (int score : scores) total += score;
double average = (double) total / scores.length;
System.out.println("Average: " + average);
Try it yourself: Find the minimum, maximum and average of a non-empty array of scores.
MODULE 06 / 12 · CONCEPT EXPLAINED

Classes, objects, constructors and encapsulation

A class defines fields and methods; an object is an instance created from that class. Keep fields private and expose methods that protect valid state. A constructor establishes the object’s required values. Use this to distinguish a field from a parameter when names match.

Follow this example
final class BankAccount {
    private final String owner;
    private int balance;

    BankAccount(String owner) { this.owner = owner; }
    void deposit(int amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }
    int balance() { return balance; }
}
Try it yourself: Create a Book class that validates a non-empty title and exposes a readable description.
MODULE 07 / 12 · CONCEPT EXPLAINED

Interfaces, inheritance and composition

An interface describes behavior that different classes can implement. Inheritance shares a subtype relationship but can couple child classes to parent behavior; composition lets a class use another object without claiming to be that type. Prefer interfaces and composition when they make dependencies easier to replace and test.

Follow this example
interface Notifier {
    void send(String message);
}

final class ReminderService {
    private final Notifier notifier;
    ReminderService(Notifier notifier) { this.notifier = notifier; }
    void remind() { notifier.send("Keep practising"); }
}
Try it yourself: Implement a Notifier that prints to the console and inject it into ReminderService.
MODULE 08 / 12 · CONCEPT EXPLAINED

Collections and choosing the right data structure

The Collections Framework provides lists, sets and maps for common data tasks. Use List when order and duplicates matter, Set for unique members, and Map for key-value lookup. Choose an implementation based on ordering and access needs, not habit; understand equality when using objects as set members or map keys.

Follow this example
import java.util.*;

List<String> topics = new ArrayList<>(List.of("types", "loops"));
Set<String> unique = new HashSet<>(topics);
Map<String, Integer> minutes = new HashMap<>();
minutes.put("types", 25);
System.out.println(unique + " / " + minutes.get("types"));
Try it yourself: Count words in a sentence with a Map and print each word with its frequency.
MODULE 09 / 12 · CONCEPT EXPLAINED

Generics, enums and records

Generics let classes and methods work with typed values while preserving compile-time checks. An enum represents a fixed set of named options. A record is a concise data carrier whose components define its state; it is a good fit for simple immutable data, not every domain object.

Follow this example
enum Status { TODO, IN_PROGRESS, DONE }

record Lesson(String title, int minutes) {}

List<Lesson> plan = List.of(new Lesson("Collections", 30));
Status status = Status.TODO;
System.out.println(plan.getFirst().title() + " - " + status);
Try it yourself: Represent a task with a record and use an enum for its status.
MODULE 10 / 12 · CONCEPT EXPLAINED

Exceptions, validation and resource safety

Exceptions represent exceptional conditions and let a caller respond at the right boundary. Use checked exceptions when callers are expected to recover from an operation, and unchecked exceptions for invalid state or programmer errors. Use try-with-resources for closeable resources such as files and database connections.

Follow this example
try (var reader = java.nio.file.Files.newBufferedReader(java.nio.file.Path.of("notes.txt"))) {
    System.out.println(reader.readLine());
} catch (java.io.IOException error) {
    System.err.println("Could not read notes: " + error.getMessage());
}
Try it yourself: Read a file safely and show a useful message if the path is missing.
MODULE 11 / 12 · CONCEPT EXPLAINED

Lambdas, streams and Optional

A lambda provides an implementation of a functional interface. Streams describe a pipeline such as filter, map and collect; they are useful for transformations but can obscure side effects or simple loops. Optional models a value that may be absent in some APIs and should be handled explicitly.

Follow this example
List<String> longTopics = topics.stream()
    .filter(topic -> topic.length() > 4)
    .map(String::toUpperCase)
    .toList();
System.out.println(longTopics);
Try it yourself: Filter a list of scores to passing values, map them to labels and calculate a summary.
MODULE 12 / 12 · CONCEPT EXPLAINED

Packages, testing, concurrency and next steps

Packages group related types and help prevent name collisions. Build tools such as Maven or Gradle manage dependencies, compilation and test execution. Write tests around observable behavior. For concurrency, begin with executors and higher-level APIs; protect shared mutable state and avoid creating an unbounded thread per task.

Follow this example
import java.util.concurrent.*;

try (var executor = Executors.newFixedThreadPool(2)) {
    Future<Integer> result = executor.submit(() -> 20 + 22);
    System.out.println(result.get());
} catch (InterruptedException error) {
    Thread.currentThread().interrupt();
} catch (ExecutionException error) {
    throw new RuntimeException(error.getCause());
}
Try it yourself: Build a small console library tracker with packages, validation, a handful of unit tests and a README.
PUT THE MODULES TOGETHER

Your final project

Build a console-based library tracker with validated models, collections, file persistence and unit tests. Write down what the project should do, build it in small steps, and include a README that explains how to run it.

Find a guided course →

Official documentation and further reading

Use primary documentation for current language rules and version changes. The examples in this guide are learning starting points; verify details for the exact runtime and browser support your project needs.

Frequently asked questions

Should beginners install Java 27 or Java 25?

Java 27 is the latest feature release, while Java 25 is the current LTS release in this snapshot. Use the version expected by your course or employer; choose LTS when long support is the priority.

Do I need to learn object-oriented programming first?

Start with variables, conditions, loops and methods, then learn classes and interfaces. Small programs make those concepts easier to understand.