Skip to content
Java examples 4 min read

Code Examples

A collection of small, self-contained Java programs you can copy, compile, and run. Each example targets a single concept, prints its result, and is written the way you’d actually write it on the job. Every snippet assumes Java 17+.

Run any example with java Example.java (single-file source mode, JDK 11+). No build tool required.

FizzBuzz

The classic warm-up: print numbers 1–15, replacing multiples of 3 with Fizz, multiples of 5 with Buzz, and multiples of both with FizzBuzz.

public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            String out = "";
            if (i % 3 == 0) out += "Fizz";
            if (i % 5 == 0) out += "Buzz";
            System.out.println(out.isEmpty() ? i : out);
        }
    }
}

Building the output by concatenation avoids the nested if/else ladder and naturally handles the “both” case.

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Reverse a String

Reverse a string without allocating intermediate objects in a loop. StringBuilder.reverse() is the idiomatic, O(n) approach.

public class ReverseString {
    static String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(reverse("DevCraftly"));
    }
}

Prefer StringBuilder over String += c in a loop. String concatenation in a loop is O(n²) because each += creates a new immutable String.

Output:

yltfarCveD

Check Palindrome

A palindrome reads the same forwards and backwards. We compare characters from both ends inward, ignoring case and non-letters so phrases like “A man, a plan, a canal: Panama” pass.

public class Palindrome {
    static boolean isPalindrome(String input) {
        String s = input.toLowerCase().replaceAll("[^a-z0-9]", "");
        int i = 0, j = s.length() - 1;
        while (i < j) {
            if (s.charAt(i++) != s.charAt(j--)) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
        System.out.println(isPalindrome("Java"));
    }
}

The two-pointer scan is O(n) time and O(1) extra space (beyond the normalized copy), which beats reversing and comparing the whole string.

Output:

true
false

Find Duplicates in an Array

Track seen elements in a HashSet. Set.add returns false when the value was already present, giving us duplicate detection in a single pass.

import java.util.*;

public class FindDuplicates {
    static Set<Integer> duplicates(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        Set<Integer> dups = new LinkedHashSet<>();
        for (int n : nums) {
            if (!seen.add(n)) dups.add(n);
        }
        return dups;
    }

    public static void main(String[] args) {
        int[] data = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        System.out.println(duplicates(data));
    }
}

Using a LinkedHashSet for the result preserves first-seen order and de-duplicates the duplicates themselves (so a value appearing three times is reported once).

Output:

[1, 5, 3]

Word Frequency Counter (Streams)

Count how often each word appears using the Streams API and Collectors.groupingBy with a downstream counting() collector — declarative and concise.

import java.util.*;
import java.util.stream.*;

public class WordFrequency {
    public static void main(String[] args) {
        String text = "the quick brown fox the lazy dog the fox";

        Map<String, Long> freq = Arrays.stream(text.split("\\s+"))
            .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

        freq.entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
                    .thenComparing(Map.Entry.comparingByKey()))
            .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
    }
}

We sort by count descending, then alphabetically as a tiebreaker so the output is deterministic.

Output:

the: 3
fox: 2
brown: 1
dog: 1
lazy: 1
quick: 1

Read a File and Count Lines

Use Files.lines, which returns a lazy Stream<String> backed by a file handle. The try-with-resources block guarantees the underlying stream is closed.

import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;

public class CountLines {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("notes.txt");
        // Create a sample file so the example is self-contained.
        Files.write(path, "alpha\nbeta\ngamma\n".getBytes());

        try (Stream<String> lines = Files.lines(path)) {
            long count = lines.count();
            System.out.println("Lines: " + count);
        }
    }
}

Always close Files.lines with try-with-resources. Unlike Files.readAllLines, it holds an open file descriptor until the stream is closed.

Output:

Lines: 3

Fibonacci (Iterative + Recursive)

Two implementations of the same sequence. The iterative version runs in O(n) time and O(1) space. The naive recursive version is elegant but O(2ⁿ) — shown for contrast, not for production.

public class Fibonacci {
    static long iterative(int n) {
        long a = 0, b = 1;
        for (int i = 0; i < n; i++) {
            long next = a + b;
            a = b;
            b = next;
        }
        return a;
    }

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

    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++) {
            System.out.print(iterative(i) + " ");
        }
        System.out.println();
        System.out.println("recursive(10) = " + recursive(10));
    }
}

For real workloads prefer the iterative form (or memoization). The recursive form recomputes the same subproblems exponentially.

Output:

0 1 1 2 3 5 8 13 21 34 55 
recursive(10) = 55

Sort a List of Objects with Comparator

Sort domain objects using the fluent Comparator builders introduced in Java 8. Here we sort employees by department, then by salary descending, then by name.

import java.util.*;

record Employee(String name, String dept, int salary) {}

public class SortObjects {
    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>(List.of(
            new Employee("Aisha", "Eng", 120_000),
            new Employee("Bilal", "Eng", 95_000),
            new Employee("Chen",  "Ops", 95_000),
            new Employee("Diego", "Ops", 110_000)
        ));

        staff.sort(Comparator.comparing(Employee::dept)
            .thenComparing(Comparator.comparingInt(Employee::salary).reversed())
            .thenComparing(Employee::name));

        staff.forEach(e -> System.out.println(
            e.dept() + " | " + e.name() + " | " + e.salary()));
    }
}

Comparator.comparing(...).thenComparing(...) reads top-to-bottom as your sort priority, which is far clearer than a hand-written multi-field compare method.

Output:

Eng | Aisha | 120000
Eng | Bilal | 95000
Ops | Diego | 110000
Ops | Chen | 95000
Last updated June 1, 2026
Was this helpful?