JvJava

Java: Basics – code examples

Contents

Hello World

Basics#print#output#mainCompare in all languages
Use case: A first test of whether the JDK and environment work.
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Every Java program needs a class with main. Start it with java Main.java.

Variables and Types

Basics#variable#type#varCompare in all languages
Use case: Store values with a fixed type and use type inference with var.
public class Main {
    public static void main(String[] args) {
        String name = "Ada";
        int alter = 36;
        double groesse = 1.68;
        boolean aktiv = true;
        var stadt = "London";   // type String is inferred
        System.out.println(name + " " + alter + " " + groesse + " " + aktiv);
        System.out.println(stadt.toUpperCase());
    }
}

Types are fixed. var only saves typing: the compiler infers the type, stadt is a String. Output: Ada 36 1.68 true and LONDON.

Date and time (java.time)

Basics#date#localdate#time
Use case: Calculate deadlines, determine time spans, format dates.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 3, 15);
        System.out.println(start.plusDays(30));
        System.out.println(start.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));
        System.out.println(ChronoUnit.DAYS.between(start, LocalDate.of(2026, 12, 24)));
    }
}

java.time is immutable and thread-safe. Output: 2026-04-14, 15.03.2026, 284 days until Christmas.