iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Syntax

Java syntax tour: classes, primitive types, control flow, methods, generics, records, var, switch expressions.

Java — syntax tour

EXAMPLE
// ===== Primitive types =====
int    age = 30;
long   id = 4_000_000_000L;
double pi = 3.14159;
boolean ok = true;
char   ch = 'A';

// Reference types: String, arrays, classes, records, enums.
String name = "Alex";
int[] nums = {1, 2, 3};

// var for local type inference (Java 10+):
var users = new java.util.ArrayList<String>();

// ===== Control flow =====
if (age >= 18) { /* ... */ } else { /* ... */ }

for (int i = 0; i < 5; i++) { /* index */ }
for (var x : nums) { /* foreach */ }

int i = 0;
while (i < 10) { i++; }
do { i--; } while (i > 0);

// Switch statement (classic):
switch (age) {
    case 0: System.out.println("baby"); break;
    default: System.out.println("older"); break;
}

// Switch EXPRESSION (Java 14+):
String size = switch (age) {
    case 0, 1 -> "baby";
    case 2, 3, 4 -> "toddler";
    default -> {
        // multi-statement arm needs yield
        var x = age * 2;
        yield x + " double";
    }
};

// Pattern matching for switch (modern):
String describe(Object o) {
    return switch (o) {
        case null -> "nothing";
        case Integer i when i < 0 -> "negative int";
        case Integer i -> "int " + i;
        case String s -> "string " + s;
        default -> "unknown";
    };
}

// ===== Classes =====
public class User {
    private final int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int id() { return id; }
    public String name() { return name; }
    public void setName(String n) { this.name = n; }
}

// ===== Records (value carriers) =====
public record Order(int id, String customer, long totalCents) {}

var o = new Order(1, "Alex", 4995);
System.out.println(o.totalCents());

// ===== Generics =====
List<Integer> nums2 = List.of(1, 2, 3);
Map<String, Integer> ages = Map.of("Alex", 30, "Sam", 25);

public static <T> T first(List<T> list) { return list.get(0); }

// ===== Methods + parameters =====
static int add(int a, int b) { return a + b; }
static int sumAll(int... xs) {
    int s = 0; for (var x : xs) s += x; return s;
}

// ===== try / catch / try-with-resources =====
try (var reader = java.nio.file.Files.newBufferedReader(java.nio.file.Path.of("a.txt"))) {
    System.out.println(reader.readLine());
} catch (java.io.IOException e) {
    e.printStackTrace();
}

// ===== Streams (functional-ish) =====
import java.util.stream.Collectors;
var evens = java.util.List.of(1, 2, 3, 4, 5).stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * n)
    .collect(Collectors.toList());

// ===== Patterns to internalise =====
// - final on locals + params; documents intent
// - records for DTOs / value types
// - Switch expressions with arrow syntax; pattern matching where useful
// - Streams for transforms; for loops for I/O-driven code

// ===== Pitfalls =====
// - == on String -> compares references; use .equals()
// - Autoboxing in hot loops -> garbage
// - Catching Exception broadly -> swallows real bugs
// - Mutable static state -> testing nightmares

Why it matters

Modern Java reads well: var, records, switch expressions, streams. Learn the primitive + reference types, the control flow, generics, and pattern matching for switch. With those reflexes, almost every Java file you read maps cleanly to the language model.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
public class Hello {
    public static void main(String[] args) {
        String name = "Ada";
        System.out.println("Hello, " + name);
    }
}
Try it Yourself »

Discussion

Loading…