Skip to main content
Java · lesson 1 of 66
Open the Java page →
Java beginner Lesson 1 of 66

Introduction to Java

What Java is, where it's used, how Java code is structured, and a complete roadmap for learning Java from beginner to advanced.

By SkillByExample · Updated

What Is Java?

Java is a statically typed, object-oriented, compiled-to-bytecode language created by James Gosling at Sun Microsystems in 1995. Its defining promise — “Write Once, Run Anywhere” — means Java code compiles to bytecode that runs on any machine with a Java Virtual Machine (JVM), regardless of operating system. This portability, combined with strong typing and a rich standard library, made Java one of the most widely deployed languages in history. Today it powers everything from Android smartphones to billion-dollar banking systems.

Your Code (.java)
      │
      ▼  javac (compiler)
  Bytecode (.class)
      │
      ▼  JVM (Windows / macOS / Linux)
  Program runs

Three decades later, Java powers:

DomainExamples
Android appsMost native Android apps are written in Java or Kotlin
Enterprise backendsSpring Boot, Jakarta EE microservices
Big dataApache Kafka, Hadoop, Spark (JVM)
Cloud infrastructureAWS SDK, Google Cloud client libs
Financial systemsBanks and trading platforms — Java’s predictable performance and strong typing make it a default choice
Developer toolingGradle, IntelliJ IDEA, Jenkins are written in Java

How Java Code Is Structured

Every Java program lives inside a class, and execution starts in a method called main. The examples in this lesson were run with JDK 21.

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Save it as Hello.java. The classic two steps compile it to bytecode and run that on the JVM; since Java 11 a single file can also be launched directly:

$ javac Hello.java
$ ls
Hello.class
Hello.java
$ java Hello
Hello, World!
$ java Hello.java
Hello, World!

javac produced Hello.class, the portable bytecode; java Hello takes a class name, not a file name. java Hello.java compiles in memory and runs in one step, leaving no .class file behind — the rest of this course uses that form.

The file name must match the public class

public class Greeter {
    public static void main(String[] args) {
        System.out.println("Hi");
    }
}
$ javac Hello.java
Hello.java:1: error: class Greeter is public, should be declared in a file named Greeter.java
public class Greeter {
       ^
1 error

Saved as Hello.java, a public class Greeter doesn’t compile with javac. Rename the file or the class so they match. (The single-file launcher is more lenient, but projects built with javac, Maven or Gradle always enforce the rule.)

Anatomy of a program

A typical class has fields (data), a constructor (setup), methods (behaviour) and, for a program’s entry point, main.

import java.util.ArrayList;
import java.util.List;

public class StudentRoster {
    private final String courseName;                        // fields
    private final List<String> students = new ArrayList<>();

    public StudentRoster(String courseName) {               // constructor
        this.courseName = courseName;
    }

    public void enroll(String name) {                       // methods
        students.add(name);
        System.out.println(name + " enrolled in " + courseName);
    }

    public void printRoster() {
        System.out.println("--- " + courseName + " (" + students.size() + ") ---");
        for (int i = 0; i < students.size(); i++) {
            System.out.println((i + 1) + ". " + students.get(i));
        }
    }

    public static void main(String[] args) {                // entry point
        StudentRoster roster = new StudentRoster("Java Fundamentals");
        roster.enroll("Alice");
        roster.enroll("Bob");
        roster.printRoster();
    }
}
$ java StudentRoster.java
Alice enrolled in Java Fundamentals
Bob enrolled in Java Fundamentals
--- Java Fundamentals (2) ---
1. Alice
2. Bob

main is static, so it runs before any StudentRoster exists and has to create one with new. import lines make List and ArrayList from the java.util package available by short name. Real projects also start files with a package line, such as package com.example.school;, which places the class in a folder-like namespace.

Static typing in one example

Every variable has a type fixed at compile time. Mismatches are compile errors, found before the program ever runs.

public class Types {
    public static void main(String[] args) {
        int age = 25;
        double salary = 72500.50;
        boolean active = true;
        String name = "Alice";
        var city = "Lisbon";                 // type inferred as String

        System.out.println(name + ", " + age + ", " + salary + ", " + active + ", " + city);
        age = "twenty-six";
    }
}
$ java Types.java
Types.java:10: error: incompatible types: String cannot be converted to int
        age = "twenty-six";
              ^
1 error
error: compilation failed

Even the println before it didn’t run: the whole file must compile first. var is not dynamic typing — city is a String forever. Remove the last line and the program prints Alice, 25, 72500.5, true, Lisbon.

Control flow, arrays and strings at a glance

Each of these gets a full lesson; this is a preview of how they read.

public class Preview {
    public static void main(String[] args) {
        int[] scores = {95, 82, 78, 91, 67};
        int total = 0;
        for (int score : scores) {
            String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C or below";
            System.out.println(score + " -> " + grade);
            total += score;
        }
        System.out.printf("average %.1f of %d scores%n", (double) total / scores.length, scores.length);

        String s = "Hello, Java!";
        System.out.println(s.toUpperCase() + " " + s.length() + " " + s.substring(7, 11));
        String day = "SATURDAY";
        String type = switch (day) {
            case "SATURDAY", "SUNDAY" -> "weekend";
            default -> "weekday";
        };
        System.out.println(day + " is a " + type);
    }
}
$ java Preview.java
95 -> A
82 -> B
78 -> C or below
91 -> A
67 -> C or below
average 82.6 of 5 scores
HELLO, JAVA! 12 Java
SATURDAY is a weekend

(double) total / scores.length converts before dividing; without the cast, total / scores.length is an int, and %.1f would throw IllegalFormatConversionException. substring(7, 11) takes characters 7 to 10 — the end index is exclusive.

Practice

  1. Write Greeting.java that prints Hello, <name>! for a name given on the command line, or Hello, stranger! when none is given.
Solution
public class Greeting {
    public static void main(String[] args) {
        String name = args.length > 0 ? args[0] : "stranger";
        System.out.println("Hello, " + name + "!");
    }
}
$ java Greeting.java Ada
Hello, Ada!
$ java Greeting.java
Hello, stranger!

Words after the file name arrive in args; with none, args is an empty array, not null.

  1. Add a drop(String name) method to StudentRoster that removes a student and prints whether they were enrolled.
Solution
import java.util.ArrayList;
import java.util.List;

public class Roster2 {
    private final List<String> students = new ArrayList<>(List.of("Alice", "Bob"));

    void drop(String name) {
        boolean removed = students.remove(name);
        System.out.println(name + (removed ? " dropped" : " was not enrolled") + " -> " + students);
    }

    public static void main(String[] args) {
        Roster2 r = new Roster2();
        r.drop("Bob");
        r.drop("Zoe");
    }
}
$ java Roster2.java
Bob dropped -> [Alice]
Zoe was not enrolled -> [Alice]

List.remove(Object) returns true only if something was removed, which tells you which message to print.

  1. Compile Hello.java with javac -d out and run it from the output folder with -cp.
Solution
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello from " + System.getProperty("java.version").split("\\.")[0]);
    }
}
$ javac -d out Hello.java
$ ls out
Hello.class
$ java -cp out Hello
Hello from 21

-d chooses where .class files go, and -cp (classpath) tells java where to look for them. This is exactly what Maven and Gradle do for you with target/ and build/.

Java Learning Roadmap

Work through these tutorials in order. Each one builds on the previous.

Module 1 — Getting Started

  1. Introduction to Java ← you are here
  2. Setting Up Java — install JDK, IntelliJ IDEA, first program
  3. Data Types in Java — primitives, wrappers, type casting, Strings
  4. Variables and Operators — operators, user input, Math class
  5. Control Flow — if/else, switch, for/while/do-while, break/continue
  6. Arrays — 1D/2D arrays, sorting, searching
  7. Strings — String methods, StringBuilder, regex
  8. Methods in Java — parameters, return types, recursion, scope

Module 2 — Object-Oriented Programming

  1. OOP — Complete Guide — overview and learning path for all OOP concepts
  2. Introduction to OOP — classes, objects, constructors, this keyword
  3. Encapsulation — access modifiers, getters/setters, immutability
  4. Inheritance — extends, super, method overriding, final
  5. Polymorphism — runtime dispatch, @Override, overloading
  6. Abstraction — abstract classes, interfaces, default methods

Module 3 — Intermediate OOP

  1. Interfaces — Deep Dive — segregation, functional interfaces, mocks
  2. Abstract Classes — template method pattern, shared state
  3. Method Overloading — compile-time polymorphism, varargs
  4. Composition vs Inheritance — Decorator, DI, mixins

Module 4 — Advanced OOP and Design

  1. SOLID Principles — five foundational design rules with examples
  2. Design Patterns — Singleton, Factory, Builder, Observer, Strategy
  3. Generics and OOP — bounded types, wildcards, PECS, type erasure

Module 5 — Intermediate Java

  1. Exception Handling — try/catch/finally, custom exceptions
  2. Collections Framework — ArrayList, HashMap, Set, Queue
  3. File Handling — File API, BufferedReader/Writer, NIO.2
  4. Java 8 Features — Lambdas, Streams, Optional, Date/Time API
  5. Multithreading — Threads, Executor, CompletableFuture

Module 6 — Tools and Testing

  1. JDBC — embedded H2 database, CRUD, PreparedStatement, transactions
  2. Maven — dependency management, pom.xml, build lifecycle
  3. Gradle — build scripts, Kotlin DSL, tasks
  4. Unit Testing — JUnit 5, Mockito, parameterized tests
  5. Logging — SLF4J, Logback, structured logging, MDC

Module 7 — Spring Boot

  1. Interview Preparation — JVM, GC, collections internals, Java 8 Q&A
  2. Spring Boot — Introduction — setup, starters, profiles, actuator
  3. Dependency Injection — IoC container, beans, scopes, @Value
  4. REST APIs — controllers, path variables, ResponseEntity
  5. Validation — Bean Validation, custom constraints, error responses
  6. Spring Data JPA — entities, repositories, JPQL, pagination
  7. Exception Handling in Spring — @ControllerAdvice, RFC 7807
  8. Spring Security — authentication, authorization, password encoding
  9. JWT Authentication — token generation, filter, refresh tokens
  10. Dockerizing Spring Boot — Dockerfile, multi-stage, Docker Compose

Start with Setting Up Java to get your development environment ready.

Frequently Asked Questions

Do I need to install anything to write Java?
Yes. Install the JDK (Java Development Kit) — it includes the compiler (javac) and the JVM. Download it from adoptium.net for free. Most developers also use an IDE like IntelliJ IDEA or VS Code.
What is the difference between JDK, JRE, and JVM?
JVM (Java Virtual Machine) runs compiled Java bytecode. JRE (Java Runtime Environment) is the JVM plus the standard library — enough to run Java programs. JDK (Java Development Kit) is the JRE plus the compiler and dev tools — needed to write and compile Java.
Is Java still worth learning?
Yes. Java runs a large share of enterprise backends (Spring Boot), Android's ecosystem and big-data tooling such as Kafka, Hadoop and Spark. A new long-term-support release ships every two years, so the language keeps gaining features like records, pattern matching and virtual threads.
Can I run a Java file without compiling it first?
Since Java 11 you can run a single source file directly with java Hello.java. The launcher compiles it in memory and runs it, without writing a .class file. Larger programs with several files are still compiled with javac or a build tool such as Maven or Gradle.