Java Coding Challenges for Beginners with Solutions

Reading about Java only gets you so far. At some point you need to write code without a tutorial holding your hand. These challenges test your understanding of Java fundamentals and build the problem-solving skills that interviews demand.

Each challenge includes a problem description, hints if you get stuck, and a solution. Try solving each one yourself before looking at the answer. The struggle is where learning happens.

Challenge 1: FizzBuzz

FizzBuzz is the classic programming interview question. It filters out candidates who can’t translate simple logic into code.

Problem: Print numbers from 1 to 100. For multiples of 3, print “Fizz” instead of the number. For multiples of 5, print “Buzz”. For multiples of both 3 and 5, print “FizzBuzz”.

Example output:

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

Hints

Use the modulo operator (%) to check divisibility. A number is divisible by 3 if number % 3 == 0.

Order matters. Check the “both” condition first, or you’ll never reach it.

Solution

public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            if (i % 3 == 0 && i % 5 == 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);
            }
        }
    }
}

The key insight: check i % 3 == 0 && i % 5 == 0 before checking each condition separately. If you check i % 3 == 0 first, numbers like 15 print “Fizz” and never reach the FizzBuzz case.

Challenge 2: Reverse a String

Problem: Write a method that takes a string and returns it reversed. “hello” becomes “olleh”.

Constraint: Don’t use StringBuilder’s reverse() method. Build the solution yourself.

Hints

Strings are immutable in Java. You’ll need to build a new string character by character.

You can access individual characters with charAt(index). The last character is at index length() - 1.

Solution

public class ReverseString {
    public static String reverse(String input) {
        StringBuilder result = new StringBuilder();
        for (int i = input.length() - 1; i >= 0; i--) {
            result.append(input.charAt(i));
        }
        return result.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(reverse("hello"));     // olleh
        System.out.println(reverse("Java"));      // avaJ
        System.out.println(reverse("12345"));     // 54321
        System.out.println(reverse(""));          // (empty string)
    }
}

This iterates backward through the string, appending each character to a StringBuilder. Using StringBuilder instead of string concatenation avoids creating many intermediate String objects.

Challenge 3: Find the Maximum

Problem: Write a method that finds the largest number in an array of integers. Assume the array has at least one element.

Hints

Start by assuming the first element is the maximum. Then check each remaining element.

Solution

public class FindMaximum {
    public static int findMax(int[] numbers) {
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        return max;
    }
    
    public static void main(String[] args) {
        int[] test1 = {3, 7, 2, 9, 1};
        int[] test2 = {-5, -2, -10, -1};
        int[] test3 = {42};
        
        System.out.println(findMax(test1));  // 9
        System.out.println(findMax(test2));  // -1
        System.out.println(findMax(test3));  // 42
    }
}

Don’t initialize max to 0. If all numbers are negative, you’d incorrectly return 0. Always initialize to an actual element from the array.

Challenge 4: Count Vowels

Problem: Write a method that counts how many vowels (a, e, i, o, u) appear in a string. Count both uppercase and lowercase vowels.

Hints

Convert the string to lowercase first to simplify your checks.

You can check if a character is a vowel using a series of comparisons or by checking if it exists in a string of vowels.

Solution

public class CountVowels {
    public static int countVowels(String input) {
        int count = 0;
        String lower = input.toLowerCase();
        
        for (int i = 0; i < lower.length(); i++) {
            char c = lower.charAt(i);
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                count++;
            }
        }
        return count;
    }
    
    public static void main(String[] args) {
        System.out.println(countVowels("Hello World"));     // 3
        System.out.println(countVowels("AEIOU"));           // 5
        System.out.println(countVowels("rhythm"));          // 0
        System.out.println(countVowels("Programming"));     // 3
    }
}

An alternative approach uses indexOf:

public static int countVowels(String input) {
    int count = 0;
    String vowels = "aeiouAEIOU";
    
    for (int i = 0; i < input.length(); i++) {
        if (vowels.indexOf(input.charAt(i)) != -1) {
            count++;
        }
    }
    return count;
}

Challenge 5: Palindrome Check

Problem: Write a method that returns true if a string is a palindrome (reads the same forward and backward). Ignore case and spaces.

Examples: “racecar” is a palindrome. “Race Car” is a palindrome (ignoring case and spaces). “hello” is not.

Hints

First, clean the string: remove spaces and convert to lowercase.

Compare the first character to the last, second to second-last, and so on.

Solution

public class Palindrome {
    public static boolean isPalindrome(String input) {
        String cleaned = input.replaceAll(" ", "").toLowerCase();
        
        int left = 0;
        int right = cleaned.length() - 1;
        
        while (left < right) {
            if (cleaned.charAt(left) != cleaned.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    
    public static void main(String[] args) {
        System.out.println(isPalindrome("racecar"));    // true
        System.out.println(isPalindrome("Race Car"));   // true
        System.out.println(isPalindrome("hello"));      // false
        System.out.println(isPalindrome("A man a plan a canal Panama")); // true
    }
}

The two-pointer approach is efficient. You only traverse half the string, and you exit early when a mismatch is found.

Challenge 6: Sum of Digits

Problem: Write a method that calculates the sum of all digits in a positive integer. For 1234, return 10 (1+2+3+4).

Hints

Use modulo 10 to extract the last digit. Use integer division by 10 to remove the last digit.

Solution

public class SumDigits {
    public static int sumDigits(int number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10;  // Add last digit
            number /= 10;        // Remove last digit
        }
        return sum;
    }
    
    public static void main(String[] args) {
        System.out.println(sumDigits(1234));   // 10
        System.out.println(sumDigits(999));    // 27
        System.out.println(sumDigits(5));      // 5
        System.out.println(sumDigits(10001));  // 2
    }
}

This technique of using % 10 and / 10 to process digits appears frequently in coding challenges. Memorize it.

Challenge 7: Prime Number Check

Problem: Write a method that returns true if a number is prime, false otherwise. A prime number is greater than 1 and divisible only by 1 and itself.

Hints

You don’t need to check all numbers up to n. If n has a factor larger than its square root, it must also have a factor smaller than its square root.

Handle edge cases: numbers less than 2 are not prime.

Solution

public class PrimeCheck {
    public static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        if (n == 2) {
            return true;
        }
        if (n % 2 == 0) {
            return false;
        }
        
        for (int i = 3; i <= Math.sqrt(n); i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        System.out.println(isPrime(2));    // true
        System.out.println(isPrime(17));   // true
        System.out.println(isPrime(18));   // false
        System.out.println(isPrime(1));    // false
        System.out.println(isPrime(97));   // true
    }
}

The optimization of checking only up to the square root and skipping even numbers makes this efficient even for large numbers.

Challenge 8: Fibonacci Sequence

Problem: Write a method that returns the nth number in the Fibonacci sequence. The sequence starts 0, 1, 1, 2, 3, 5, 8, 13… where each number is the sum of the two before it.

Use n=0 for the first number (0), n=1 for the second (1), and so on.

Hints

Track the previous two numbers. In each iteration, calculate the next number and shift your tracking variables.

Solution

public class Fibonacci {
    public static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        
        int prev = 0;
        int current = 1;
        
        for (int i = 2; i <= n; i++) {
            int next = prev + current;
            prev = current;
            current = next;
        }
        return current;
    }
    
    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++) {
            System.out.print(fibonacci(i) + " ");
        }
        // Output: 0 1 1 2 3 5 8 13 21 34 55
    }
}

This iterative approach runs in O(n) time. A recursive solution is simpler to write but runs in O(2^n) time without memoization, making it impractical for large n.

Challenge 9: Remove Duplicates

Problem: Write a method that takes an ArrayList of integers and returns a new ArrayList with duplicates removed. Preserve the original order.

Hints

Track which numbers you’ve already seen. A Set provides fast lookups for this purpose.

Solution

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class RemoveDuplicates {
    public static ArrayList<Integer> removeDuplicates(ArrayList<Integer> list) {
        ArrayList<Integer> result = new ArrayList<>();
        Set<Integer> seen = new HashSet<>();
        
        for (Integer num : list) {
            if (!seen.contains(num)) {
                seen.add(num);
                result.add(num);
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(2);
        numbers.add(3);
        numbers.add(1);
        numbers.add(4);
        
        System.out.println(removeDuplicates(numbers)); // [1, 2, 3, 4]
    }
}

The HashSet provides O(1) lookups, making the overall algorithm O(n). Without the Set, you’d need nested loops and O(n²) time.

Challenge 10: Word Frequency Counter

Problem: Write a method that takes a sentence and returns a Map containing each word and how many times it appears. Convert words to lowercase for counting.

Hints

Split the sentence into words using split(" ") or split("\\s+") for multiple spaces.

Use a HashMap to store word counts. Check if the word exists before incrementing.

Solution

import java.util.HashMap;
import java.util.Map;

public class WordFrequency {
    public static Map<String, Integer> countWords(String sentence) {
        Map<String, Integer> frequency = new HashMap<>();
        String[] words = sentence.toLowerCase().split("\\s+");
        
        for (String word : words) {
            if (word.isEmpty()) {
                continue;
            }
            if (frequency.containsKey(word)) {
                frequency.put(word, frequency.get(word) + 1);
            } else {
                frequency.put(word, 1);
            }
        }
        return frequency;
    }
    
    public static void main(String[] args) {
        String text = "the quick brown fox jumps over the lazy dog the fox";
        Map<String, Integer> counts = countWords(text);
        
        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

A cleaner version uses getOrDefault:

for (String word : words) {
    if (!word.isEmpty()) {
        frequency.put(word, frequency.getOrDefault(word, 0) + 1);
    }
}

Practice Tips

Type out solutions instead of copying them. The physical act of typing builds muscle memory and forces you to process each line.

After solving a challenge, try variations. Can you solve FizzBuzz without using if-else? Can you reverse a string recursively? Variations deepen understanding.

Time yourself. Interview coding happens under pressure. Practice working through problems in 15-20 minutes.

When stuck, struggle for at least 15 minutes before checking hints. The frustration of being stuck followed by the relief of solving it creates stronger memories than reading solutions passively.

What’s Next

These challenges cover fundamentals: loops, conditionals, strings, arrays, and basic data structures. Once you’re comfortable with them, move on to object-oriented challenges that test class design and inheritance.

For interview preparation, practice explaining your thought process out loud while coding. Interviewers care as much about how you think as whether you get the right answer.


Related: 10 Java Interview Questions | Java Methods

Sources

  • Oracle. “The Java Tutorials.” docs.oracle.com
  • Cracking the Coding Interview by Gayle Laakmann McDowell
Scroll to Top