Java examples

Practical, runnable Java snippets. Click any example to open it in the interactive Java playground, then edit the code and compile it against a real JDK.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello from Java!");

        for (int i = 0; i < 10; i++) {
            System.out.println("fib(" + i + ") = " + fib(i));
        }
    }

    static long fib(int n) {
        if (n < 2) {
            return n;
        }
        return fib(n - 1) + fib(n - 2);
    }
}

Run a Java program that prints Hello World and computes Fibonacci numbers.

Open in Java playground
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String[] words = {"banana", "apple", "cherry", "apple", "banana", "apple"};

        // Count occurrences with a HashMap.
        Map<String, Integer> counts = new HashMap<>();
        for (String w : words) {
            counts.merge(w, 1, Integer::sum);
        }

        // TreeMap keeps keys sorted for stable output.
        for (Map.Entry<String, Integer> e : new TreeMap<>(counts).entrySet()) {
            System.out.printf("%-8s %d%n", e.getKey(), e.getValue());
        }
    }
}

Count word occurrences using a HashMap in Java.

Open in Java playground
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        int sumOfEvenSquares = nums.stream()
                .filter(x -> x % 2 == 0)
                .mapToInt(x -> x * x)
                .sum();

        System.out.println("nums: " + nums);
        System.out.println("sum of even squares: " + sumOfEvenSquares);
    }
}

Transform and reduce a list using the Java Streams API.

Open in Java playground