10 Common Coding Interview Questions in Java

Preparing for a coding interview can be a daunting task, especially when it comes to mastering the language and concepts that are frequently tested. In this article, we will explore ten common coding interview questions in Java. Each question is accompanied by detailed code examples and their expected outputs, making it easier for you to understand and practice.

Prerequisites

Before diving into the questions, it’s important to have a basic understanding of Java programming. Familiarity with concepts such as variables, loops, conditionals, and functions will be beneficial. If you are new to Java, consider reviewing the following topics:

  • Basic syntax and structure of Java programs
  • Data types and variables
  • Control flow statements (if-else, switch)
  • Loops (for, while)
  • Functions and methods

Step-by-Step Guide to Common Coding Interview Questions

Below are ten coding interview questions that you may encounter, along with their solutions:

1. Reverse a String

Write a method that takes a string as input and returns the string reversed.

public String reverseString(String str) {
    return new StringBuilder(str).reverse().toString();
}

Expected Output: If the input is “hello”, the output will be “olleh”.

2. Check for Palindrome

Determine if a given string is a palindrome (reads the same forwards and backwards).

public boolean isPalindrome(String str) {
    String reversed = new StringBuilder(str).reverse().toString();
    return str.equals(reversed);
}

Expected Output: For the input “racecar”, the output will be true.

3. Find the Factorial of a Number

Calculate the factorial of a non-negative integer.

public int factorial(int n) {
    if (n == 0) return 1;
    return n * factorial(n - 1);
}

Expected Output: For the input 5, the output will be 120.

4. FizzBuzz Problem

Print numbers from 1 to 100. For multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz”. For numbers which are multiples of both three and five, print “FizzBuzz”.

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);
    }
}

Expected Output: The output will include “Fizz”, “Buzz”, and “FizzBuzz” at the appropriate intervals.

5. Find the Largest Element in an Array

Write a method to find the largest number in an array of integers.

public int findLargest(int[] arr) {
    int largest = arr[0];
    for (int num : arr) {
        if (num > largest) {
            largest = num;
        }
    }
    return largest;
}

Expected Output: For the input array [1, 3, 5, 7, 9], the output will be 9.

6. Count Vowels in a String

Count the number of vowels in a given string.

public int countVowels(String str) {
    int count = 0;
    for (char c : str.toCharArray()) {
        if ("aeiouAEIOU".indexOf(c) != -1) {
            count++;
        }
    }
    return count;
}

Expected Output: For the input “Hello World”, the output will be 3.

7. Merge Two Sorted Arrays

Merge two sorted arrays into a single sorted array.

public int[] mergeSortedArrays(int[] arr1, int[] arr2) {
    int[] merged = new int[arr1.length + arr2.length];
    int i = 0, j = 0, k = 0;
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) {
            merged[k++] = arr1[i++];
        } else {
            merged[k++] = arr2[j++];
        }
    }
    while (i < arr1.length) {
        merged[k++] = arr1[i++];
    }
    while (j < arr2.length) {
        merged[k++] = arr2[j++];
    }
    return merged;
}

Expected Output: Merging [1, 3, 5] and [2, 4, 6] will yield [1, 2, 3, 4, 5, 6].

8. Remove Duplicates from an Array

Remove duplicate elements from an array.

public int[] removeDuplicates(int[] arr) {
    Set set = new HashSet<>();
    for (int num : arr) {
        set.add(num);
    }
    return set.stream().mapToInt(i -> i).toArray();
}

Expected Output: For the input [1, 2, 2, 3, 4, 4], the output will be [1, 2, 3, 4].

9. Check for Anagram

Determine if two strings are anagrams of each other.

public boolean areAnagrams(String str1, String str2) {
    char[] arr1 = str1.toCharArray();
    char[] arr2 = str2.toCharArray();
    Arrays.sort(arr1);
    Arrays.sort(arr2);
    return Arrays.equals(arr1, arr2);
}

Expected Output: For the inputs “listen” and “silent”, the output will be true.

10. Fibonacci Sequence

Generate the Fibonacci sequence up to a specified number.

public List fibonacci(int n) {
    List fib = new ArrayList<>();
    int a = 0, b = 1;
    while (a <= n) {
        fib.add(a);
        int temp = a;
        a = b;
        b = temp + b;
    }
    return fib;
}

Expected Output: For the input 10, the output will be [0, 1, 1, 2, 3, 5, 8].

Conclusion

These ten coding interview questions are a great starting point for your preparation. By practicing these problems, you will not only improve your coding skills but also gain confidence for your upcoming interviews. Remember, the key to success is consistent practice and understanding the underlying concepts. Good luck!

For more resources and examples, check out the following links:

https://medium.com/@chandantechie/10-common-coding-interview-questions-using-java-d28fb3ce5eef?source=rss——data_structures-5

Continue reading on Medium »

Source: Original Article