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:
| Domain | Examples |
|---|---|
| Android apps | Every Android app is written in Java or Kotlin (JVM-based) |
| Enterprise backends | Spring Boot, Jakarta EE microservices |
| Big data | Apache Kafka, Hadoop, Spark (JVM) |
| Cloud infrastructure | AWS SDK, Google Cloud client libs |
| Financial systems | Banks and trading platforms — Java’s predictable performance and strong typing make it a default choice |
| Developer tooling | Gradle, 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
- Introduction to Java ← you are here
- Setting Up Java — install JDK, IntelliJ IDEA, first program
- Data Types in Java — primitives, wrappers, type casting, Strings
- Variables and Operators — operators, user input, Math class
- Control Flow — if/else, switch, for/while/do-while, break/continue
- Arrays — 1D/2D arrays, sorting, searching
- Strings — String methods, StringBuilder, regex
- Methods in Java — parameters, return types, recursion, scope
Module 2 — Object-Oriented Programming
- OOP — Complete Guide — overview and learning path for all OOP concepts
- Introduction to OOP — classes, objects, constructors, this keyword
- Encapsulation — access modifiers, getters/setters, immutability
- Inheritance — extends, super, method overriding, final
- Polymorphism — runtime dispatch, @Override, overloading
- Abstraction — abstract classes, interfaces, default methods
Module 3 — Intermediate OOP
- Interfaces — Deep Dive — segregation, functional interfaces, mocks
- Abstract Classes — template method pattern, shared state
- Method Overloading — compile-time polymorphism, varargs
- Composition vs Inheritance — Decorator, DI, mixins
Module 4 — Advanced OOP and Design
- SOLID Principles — five foundational design rules with examples
- Design Patterns — Singleton, Factory, Builder, Observer, Strategy
- Generics and OOP — bounded types, wildcards, PECS, type erasure
Module 5 — Intermediate Java
- Exception Handling — try/catch/finally, custom exceptions
- Collections Framework — ArrayList, HashMap, Set, Queue
- File Handling — File API, BufferedReader/Writer, NIO.2
- Java 8 Features — Lambdas, Streams, Optional, Date/Time API
- Multithreading — Threads, Executor, CompletableFuture
Module 6 — Tools and Testing
- JDBC — connect to MySQL, CRUD, PreparedStatement, transactions
- Maven — dependency management, pom.xml, build lifecycle
- Gradle — build scripts, Kotlin DSL, tasks
- Unit Testing — JUnit 5, Mockito, parameterized tests
- Logging — SLF4J, Logback, structured logging, MDC
Module 7 — Spring Boot
- Interview Preparation — JVM, GC, collections internals, Java 8 Q&A
- Spring Boot — Introduction — setup, starters, profiles, actuator
- Dependency Injection — IoC container, beans, scopes, @Value
- REST APIs — controllers, path variables, ResponseEntity
- Validation — Bean Validation, custom constraints, error responses
- Spring Data JPA — entities, repositories, JPQL, pagination
- Exception Handling in Spring — @ControllerAdvice, RFC 7807
- Spring Security — authentication, authorization, password encoding
- JWT Authentication — token generation, filter, refresh tokens
- Dockerizing Spring Boot — Dockerfile, multi-stage, Docker Compose
Start with Setting Up Java to get your development environment ready.