Before you begin
No prior programming experience is required. Install a JDK, which includes the compiler and tools needed to run Java programs.
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.
No prior programming experience is required. Install a JDK, which includes the compiler and tools needed to run Java programs.
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.
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.
class Main {
public static void main(String[] args) {
System.out.println("Hello, Java");
}
}
// Save as Main.java, then run: java Main.javaJava 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.
int lessons = 4;
double score = 87.5;
boolean passed = score >= 40;
String learner = "Asha";
System.out.println(learner + ": " + lessons + ", passed=" + passed);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.
int score = 72;
String result = score >= 60 ? "Pass" : "Retry";
for (int number = 1; number <= 5; number++) {
System.out.println(number + " → " + result);
}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.
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));
}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.
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);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.
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; }
}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.
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"); }
}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.
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"));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.
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);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.
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());
}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.
List<String> longTopics = topics.stream()
.filter(topic -> topic.length() > 4)
.map(String::toUpperCase)
.toList();
System.out.println(longTopics);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.
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());
}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 →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.
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.
Start with variables, conditions, loops and methods, then learn classes and interfaces. Small programs make those concepts easier to understand.