JvJava

Java exercises with solutions

Solve in editor

Write your solution right in the browser.

Open exercises with editor

1. Even numbers Beginner

Print all even numbers from 1 to 10 – each on its own line.

Expected output: 2 ⏎ 4 ⏎ 6 ⏎ 8 ⏎ 10

Note

Counting loop with a step of 2: for (int i = 2; i <= 10; i += 2). Or check with i % 2 == 0.

Show sample solution
public class Main {
    public static void main(String[] args) {
        for (int i = 2; i <= 10; i += 2) {
            System.out.println(i);
        }
    }
}

2. FizzBuzz (1–15) Beginner

Print the numbers 1 to 15. For multiples of 3 print Fizz instead, for multiples of 5 Buzz, for both FizzBuzz.

Expected output: 1 ⏎ 2 ⏎ Fizz ⏎ 4 ⏎ Buzz ⏎ Fizz ⏎ 7 ⏎ 8 ⏎ Fizz ⏎ Buzz ⏎ 11 ⏎ Fizz ⏎ 13 ⏎ 14 ⏎ FizzBuzz

Note

Check the "divisible by 15" case first, then 3 and 5.

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

3. Reverse a word Beginner

Reverse the string "Java" and print it.

Expected output: avaJ

Note

StringBuilder has a method reverse().

Show sample solution
public class Main {
    public static void main(String[] args) {
        String wort = "Java";
        System.out.println(new StringBuilder(wort).reverse());
    }
}

4. Sum of squares Beginner

Compute the sum of the squares of the numbers 1 to 10 and print it.

Expected output: 385

Note

Either a loop with summe += i * i; or IntStream.rangeClosed(1, 10).map(x -> x * x).sum().

Show sample solution
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int summe = IntStream.rangeClosed(1, 10).map(x -> x * x).sum();
        System.out.println(summe);
    }
}

5. Palindrome method Intermediate

Write a method istPalindrom(String text) that returns true if the text reads the same forwards and backwards (ignore case). Print istPalindrom("Anna") and istPalindrom("Java").

Expected output: true ⏎ false

Note

Convert with toLowerCase() and compare with the reversed version (StringBuilder.reverse().toString()) using equals.

Show sample solution
public class Main {
    static boolean istPalindrom(String text) {
        String t = text.toLowerCase();
        return t.equals(new StringBuilder(t).reverse().toString());
    }

    public static void main(String[] args) {
        System.out.println(istPalindrom("Anna"));
        System.out.println(istPalindrom("Java"));
    }
}

6. Most frequent word Intermediate

Find the most frequent word in "a b a c b a" and print it.

Expected output: a

Note

Count with Collectors.groupingBy(w -> w, Collectors.counting()) and then find the largest entry with Collections.max(map.entrySet(), Map.Entry.comparingByValue()).

Show sample solution
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        String text = "a b a c b a";
        Map<String, Long> zaehler = Arrays.stream(text.split(" "))
                .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
        String top = Collections.max(zaehler.entrySet(), Map.Entry.comparingByValue()).getKey();
        System.out.println(top);
    }
}

7. Primes up to 30 Intermediate

Print all prime numbers up to 30 on one line, separated by spaces.

Expected output: 2 3 5 7 11 13 17 19 23 29

Note

A number n is prime if n % d != 0 holds for all d from 2 to n-1: IntStream.range(2, n).allMatch(...). You join with Collectors.joining(" ").

Show sample solution
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        String ergebnis = IntStream.rangeClosed(2, 30)
                .filter(n -> IntStream.range(2, n).allMatch(d -> n % d != 0))
                .mapToObj(String::valueOf)
                .collect(Collectors.joining(" "));
        System.out.println(ergebnis);
    }
}

8. Sealed shapes and total area Advanced

Define a sealed interface Form with the records Quadrat(int seite) and Rechteck(int breite, int hoehe). Write a method flaeche(Form) with a switch expression (without default) and print the sum of the areas of Quadrat(3), Rechteck(2, 4) and Quadrat(1).

Expected output: 18

Note

sealed interface Form permits Quadrat, Rechteck {} and record Quadrat(int seite) implements Form {}. In the switch: case Quadrat q -> q.seite() * q.seite();. Sum up with a stream: mapToInt(Main::flaeche).sum().

Show sample solution
import java.util.List;

public class Main {
    sealed interface Form permits Quadrat, Rechteck {}
    record Quadrat(int seite) implements Form {}
    record Rechteck(int breite, int hoehe) implements Form {}

    static int flaeche(Form f) {
        return switch (f) {
            case Quadrat q -> q.seite() * q.seite();
            case Rechteck r -> r.breite() * r.hoehe();
        };
    }

    public static void main(String[] args) {
        List<Form> formen = List.of(new Quadrat(3), new Rechteck(2, 4), new Quadrat(1));
        System.out.println(formen.stream().mapToInt(Main::flaeche).sum());
    }
}