Skip to main content
Java beginner Lesson 1 of 58

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.

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 appsEvery Android app is written in Java or Kotlin (JVM-based)
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. The entry point is always a method called main. This structure might feel rigid at first, but it pays off: once you understand the pattern, you can navigate any Java codebase instantly because everything follows the same conventions.

// File: Hello.java
// Class name MUST match the filename exactly
public class Hello {

    // Entry point — Java always starts here
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Compiling and running from the terminal:

javac Hello.java   # produces Hello.class (bytecode)
java Hello         # runs it on the JVM → Hello, World!

Anatomy of a Java Program

A real Java file has several parts that work together. Understanding each section up front will make every later tutorial click faster — you’ll recognise the scaffolding and focus on the logic inside it.

// 1. Package declaration — optional, groups related classes
package com.example.learning;

// 2. Imports — bring in classes from other packages
import java.util.List;
import java.util.ArrayList;

// 3. Class declaration — one public class per file
public class StudentRoster {

    // 4. Fields — data the class holds
    private String courseName;
    private List<String> students;

    // 5. Constructor — creates an instance of the class
    public StudentRoster(String courseName) {
        this.courseName = courseName;
        this.students = new ArrayList<>();
    }

    // 6. Methods — behaviour of the class
    public void enroll(String studentName) {
        students.add(studentName);
        System.out.println(studentName + " enrolled in " + courseName);
    }

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

    // 7. Main method — program entry point
    public static void main(String[] args) {
        StudentRoster roster = new StudentRoster("Java Fundamentals");
        roster.enroll("Alice");
        roster.enroll("Bob");
        roster.enroll("Charlie");
        roster.printRoster();
    }
}

Output:

Alice enrolled in Java Fundamentals
Bob enrolled in Java Fundamentals
Charlie enrolled in Java Fundamentals
--- Java Fundamentals ---
1. Alice
2. Bob
3. Charlie

Core Language Basics

Variables and Assignment

Java is statically typed — every variable has a declared type that never changes. This is a deliberate design choice: catching type errors at compile time (before you ever run the program) eliminates a whole class of bugs that plague dynamically typed languages.

int age = 25;
double salary = 72500.50;
boolean isActive = true;
String name = "Alice";

// Java 10+ — type inference with var (type still fixed at compile time)
var items = new ArrayList<String>(); // inferred as ArrayList<String>

Control Flow

Control flow is how a program makes decisions and repeats work. Java provides if/else for branching, switch for multi-way choices, and three loop types for repetition — each suited to a different situation.

// if / else if / else
int score = 82;
String grade;
if (score >= 90)      grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else                  grade = "F";

// switch expression (Java 14+)
String day = "MONDAY";
String type = switch (day) {
    case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
    case "SATURDAY", "SUNDAY" -> "Weekend";
    default -> throw new IllegalArgumentException("Unknown day: " + day);
};

// for loop
for (int i = 0; i < 5; i++) {
    System.out.println("Count: " + i);
}

// enhanced for (for-each)
List<String> names = List.of("Alice", "Bob", "Charlie");
for (String n : names) {
    System.out.println(n);
}

// while loop
int n = 10;
while (n > 0) {
    System.out.print(n + " ");
    n -= 3;
}
// 10 7 4 1

Arrays

Arrays store multiple values of the same type in a single, indexed container. They are the most fundamental data structure in Java — understanding how they work underpins everything from collections to sorting algorithms.

// Fixed-size, same-type elements
int[] scores = {95, 82, 78, 91, 67};

System.out.println(scores[0]);        // 95
System.out.println(scores.length);    // 5

// Iterate
for (int score : scores) {
    System.out.print(score + " ");
}

// 2D array
int[][] grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
System.out.println(grid[1][2]); // 6

String Basics

Strings represent text. In Java, String is an immutable object — every “modification” creates a new instance rather than changing the original. This matters for correctness (you must reassign to capture changes) and performance (use StringBuilder for heavy string building in loops).

String s = "Hello, Java!";

System.out.println(s.length());          // 12
System.out.println(s.toUpperCase());     // HELLO, JAVA!
System.out.println(s.contains("Java")); // true
System.out.println(s.replace("Java", "World")); // Hello, World!
System.out.println(s.substring(7, 11)); // Java
System.out.println(s.indexOf("J"));     // 7

// String formatting
String msg = String.format("Name: %s, Age: %d, Score: %.1f", "Alice", 25, 98.5);
// or use text blocks (Java 15+)
String json = """
        {
            "name": "Alice",
            "age": 25
        }
        """;

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 — connect to MySQL, 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 relevant in 2024?
Yes. Java is the primary language for Android development, enterprise backends (Spring Boot), and big data tooling (Hadoop, Spark, Kafka are all written in Java/Scala). It consistently ranks in the top 3 most-used languages worldwide.