Java · lesson 1 of 66
Beginner
17- 1 Introduction to Java
- 2 Setting Up Java
- 3 Data Types in Java
- 4 Operators in Java
- 5 Variables and Operators in Java
- 6 Control Flow in Java
- 7 Arrays in Java
- 8 Functions (Methods) in Java
- 9 Strings in Java
- 10 Methods in Java
- 11 Java OOP — Complete Guide
- 12 Introduction to Object-Oriented Programming in Java
- 13 Encapsulation in Java
- 14 Inheritance in Java
- 15 Polymorphism in Java
- 17 Abstraction in Java
- 18 Error Types in Java
Intermediate
38- 16 Regular Expressions in Java
- 19 Interfaces in Java — A Deep Dive
- 20 Abstract Classes in Java
- 21 Method Overloading in Java
- 22 Composition vs Inheritance in Java
- 23 Generics in Java
- 27 Exception Handling in Java
- 28 Java Streams API
- 29 Collections Framework in Java
- 30 Optional in Java
- 31 File Handling in Java
- 32 Records in Java
- 33 Java 8 Features
- 34 Sealed Classes and Interfaces in Java
- 35 Multithreading in Java
- 37 JDBC — Database Access in Java
- 39 Maven — Java Build and Dependency Management
- 42 Gradle — Modern Java Build Tool
- 44 Unit Testing with JUnit 5 and Mockito
- 45 Logging in Java with SLF4J and Logback
- 49 Spring Boot — Introduction
- 50 Dependency Injection in Spring Boot
- 51 Java Project Ideas
- 52 Building REST APIs with Spring Boot
- 53 Validation in Spring Boot
- 54 Spring Data JPA — Database Access
- 55 Exception Handling in Spring Boot
- 56 Spring Security — Authentication and Authorization
- 57 JWT Authentication in Spring Boot
- 58 Dockerizing Spring Boot Applications
- 59 Java Enums: Beyond Simple Constants
- 60 Inner and Anonymous Classes in Java
- 61 Java Generics: Bounded Types, Wildcards, and Generic Methods
- 62 Java Date/Time API: LocalDate, LocalDateTime, and Duration
- 63 Java NIO.2: Paths, Files, and WatchService
- 64 Java Annotations: Custom Types and Meta-Information
- 65 Java Reflection: Dynamic Type Inspection and Method Invocation
- 66 Java Localization: ResourceBundle and Locale Support
Advanced
11Introduction 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:
| Domain | Examples |
|---|---|
| Android apps | Most native Android apps are written in Java or Kotlin |
| 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, 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
- Write
Greeting.javathat printsHello, <name>!for a name given on the command line, orHello, 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.
- Add a
drop(String name)method toStudentRosterthat 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.
- Compile
Hello.javawithjavac -d outand 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
- 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 — embedded H2 database, 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.