Top 5 Java String Coding Interview Questions and Solutions (Core Java + Java 8) – Part 1

Introduction :

String-based programming questions are among the most frequently asked coding problems in Java interviews because they evaluate a candidate's problem-solving ability, understanding of loops, string manipulation, collections, and Java 8 features. Whether you're preparing for a Java Developer, Spring Boot Developer, or Java Full Stack Developer interview, mastering these problems is essential.

In this article, we'll discuss five commonly asked Java String coding interview questions. For every problem, we'll explore a Core Java solution followed by a Java 8 Stream solution (where applicable). Along with the code, you'll understand the logic behind the solution, analyze its time and space complexity, and learn practical interview tips that can help you confidently explain your approach during technical interviews.



Rather than simply copying code, try solving each problem yourself before looking at the solution. This practice will improve your logical thinking and prepare you for real interview scenarios.

Let's begin with one of the most common Java interview questions.


Interview Question 1: Reverse a String in Java

🟢 Difficulty: Easy

❓ Interview Question

How do you reverse a String in Java without using the built-in StringBuilder.reverse() method?


📖 Problem Statement

Write a Java program to reverse a given string and print the reversed output.


📥 Example

Input

Java

Output

avaJ

💻 Solution 1 – Core Java

public class ReverseString {

    public static void main(String[] args) {

        String input = "Java";
        String reversed = "";

        for (int i = input.length() - 1; i >= 0; i--) {
            reversed = reversed + input.charAt(i);
        }

        System.out.println("Original String : " + input);
        System.out.println("Reversed String : " + reversed);
    }
}

Output

Original String : Java

Reversed String : avaJ

🌊 Solution 2 – Java 8 Streams

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ReverseStringStream {

    public static void main(String[] args) {

        String input = "Java";

        String reversed = IntStream.range(0, input.length())
                .mapToObj(i -> String.valueOf(input.charAt(input.length() - 1 - i)))
                .collect(Collectors.joining());

        System.out.println(reversed);
    }
}

Output

avaJ

📝 Explanation

Core Java Approach

The logic is straightforward. We start traversing the string from the last character and continue until the first character. During each iteration, we append the current character to a new string named reversed.

For the input "Java":

  • Start from index 3 → a
  • Then index 2 → v
  • Then index 1 → a
  • Finally index 0 → J

The final reversed string becomes:

avaJ

This approach is simple and is one of the most common solutions expected in Java interviews.


Java 8 Stream Approach

In Java 8, we use IntStream.range() to generate index values from 0 to length - 1. Instead of reading characters in the normal order, we calculate the reverse index using:

input.length() - 1 - i

Each character is converted into a String using String.valueOf(), and finally all characters are combined using Collectors.joining().

Although this approach is more modern and demonstrates familiarity with Java 8 Streams, interviewers generally expect candidates to first explain the loop-based solution before presenting the Stream version.


📊 Time Complexity

ApproachTime Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

📊 Space Complexity

ApproachSpace Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

💡 Interview Tip

During interviews, avoid jumping directly to the Java 8 Stream solution.

A good approach is:

  1. Explain the loop-based logic.
  2. Write the Core Java solution.
  3. Mention that the same problem can also be solved using StringBuilder or Java 8 Streams.

This demonstrates both strong fundamentals and knowledge of modern Java features.

Interview Question 2: Check Whether a String is a Palindrome

🟢 Difficulty: Easy

❓ Interview Question

How do you check whether a given String is a Palindrome in Java?


📖 Problem Statement

A palindrome is a string that reads the same forwards and backwards.

Write a Java program to check whether a given string is a palindrome.


📥 Example

Example 1

Input

madam

Output

Palindrome

Example 2

Input

java

Output

Not a Palindrome

💻 Solution 1 – Core Java

public class PalindromeString {

    public static void main(String[] args) {

        String input = "madam";
        String reversed = "";

        for (int i = input.length() - 1; i >= 0; i--) {
            reversed += input.charAt(i);
        }

        if (input.equals(reversed)) {
            System.out.println(input + " is a Palindrome");
        } else {
            System.out.println(input + " is Not a Palindrome");
        }
    }
}

Output

madam is a Palindrome

🌊 Solution 2 – Java 8 Streams

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PalindromeStringStream {

    public static void main(String[] args) {

        String input = "madam";

        String reversed = IntStream.range(0, input.length())
                .mapToObj(i -> String.valueOf(input.charAt(input.length() - 1 - i)))
                .collect(Collectors.joining());

        boolean isPalindrome = input.equals(reversed);

        System.out.println(isPalindrome
                ? input + " is a Palindrome"
                : input + " is Not a Palindrome");
    }
}

Output

madam is a Palindrome

📝 Explanation

A palindrome is a string whose reverse is exactly the same as the original string.

The basic approach is:

  1. Reverse the given string.
  2. Compare the reversed string with the original string.
  3. If both are equal, the string is a palindrome.
  4. Otherwise, it is not a palindrome.

For example:

Input  : madam
Reverse: madam

Result : Palindrome

Another example:

Input  : java
Reverse: avaj

Result : Not a Palindrome

In the Core Java solution, we use a loop to reverse the string character by character.

In the Java 8 Stream solution, we use IntStream.range() to generate indices and construct the reversed string using Streams.


📊 Time Complexity

ApproachTime Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

📊 Space Complexity

ApproachSpace Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

💡 Interview Tip

Many candidates immediately reverse the entire string.

A better approach in interviews is to mention:

"Instead of reversing the complete string, we can compare characters from both ends and stop as soon as a mismatch is found."

This reduces unnecessary operations and demonstrates optimization skills.

Example:

public static boolean isPalindrome(String str) {

    int left = 0;
    int right = str.length() - 1;

    while (left < right) {

        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }

        left++;
        right--;
    }

    return true;
}

This is often considered the most efficient interview solution.

Interview Question 3: Count Vowels and Consonants in a String

🟢 Difficulty: Easy

❓ Interview Question

How do you count the number of vowels and consonants in a given String in Java?


📖 Problem Statement

Write a Java program to count the total number of vowels and consonants present in a given string.

Note: Ignore spaces, digits, and special characters while counting.


📥 Example

Example 1

Input

Java Programming

Output

Vowels : 5
Consonants : 10

Example 2

Input

Hello World

Output

Vowels : 3
Consonants : 7

💻 Solution 1 – Core Java

public class CountVowelsAndConsonants {

    public static void main(String[] args) {

        String input = "Java Programming".toLowerCase();

        int vowels = 0;
        int consonants = 0;

        for (char ch : input.toCharArray()) {

            if (Character.isLetter(ch)) {

                if ("aeiou".indexOf(ch) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }

        System.out.println("Vowels : " + vowels);
        System.out.println("Consonants : " + consonants);
    }
}

Output

Vowels : 5
Consonants : 10

🌊 Solution 2 – Java 8 Streams

import java.util.stream.Collectors;

public class CountVowelsAndConsonantsStream {

    public static void main(String[] args) {

        String input = "Java Programming".toLowerCase();

        long vowels = input.chars()
                .filter(Character::isLetter)
                .filter(ch -> "aeiou".indexOf(ch) != -1)
                .count();

        long consonants = input.chars()
                .filter(Character::isLetter)
                .filter(ch -> "aeiou".indexOf(ch) == -1)
                .count();

        System.out.println("Vowels : " + vowels);
        System.out.println("Consonants : " + consonants);
    }
}

Output

Vowels : 5
Consonants : 10

📝 Explanation

The objective of this program is to determine how many vowels and consonants are present in a given string.

In the Core Java approach, we first convert the string to lowercase so that uppercase and lowercase letters are treated the same. Then, we iterate through each character using a for-each loop. Before counting, we check whether the character is an alphabet using Character.isLetter(). This prevents spaces, numbers, and special characters from being counted.

Next, we check whether the character exists in the string "aeiou" using the indexOf() method. If the character is found, it is counted as a vowel; otherwise, it is counted as a consonant.

In the Java 8 Stream approach, we use the chars() method to convert the string into an IntStream. We then filter only alphabetic characters and count vowels and consonants separately using the count() terminal operation.

Both approaches produce the same result, but the Stream solution offers a more functional programming style introduced in Java 8.


📊 Time Complexity

ApproachTime Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

📊 Space Complexity

ApproachSpace Complexity
    Core Java    O(1)
Java 8 Streams    O(1)

💡 Interview Tip

During interviews, many candidates forget to ignore spaces and special characters.

For example:

Java 8 @ Programming!

The interviewer expects you to count only alphabetic characters.

Always mention that you're using Character.isLetter() to handle this case. It shows that you've considered edge cases rather than just the happy path.

Interview Question 4: Remove Duplicate Characters from a String

🟡 Difficulty: Medium

❓ Interview Question

How do you remove duplicate characters from a String while preserving the original order in Java?


📖 Problem Statement

Write a Java program to remove duplicate characters from a given string while maintaining the order of their first occurrence.


📥 Example

Input

programming

Output

progamin

💻 Solution 1 – Core Java

import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateCharacters {

    public static void main(String[] args) {

        String input = "programming";

        Set<Character> set = new LinkedHashSet<>();

        for (char ch : input.toCharArray()) {
            set.add(ch);
        }

        StringBuilder result = new StringBuilder();

        for (char ch : set) {
            result.append(ch);
        }

        System.out.println("Original String : " + input);
        System.out.println("After Removing Duplicates : " + result);
    }
}

Output

Original String : programming

After Removing Duplicates : progamin

🌊 Solution 2 – Java 8 Streams

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveDuplicateCharactersStream {

    public static void main(String[] args) {

        String input = "programming";

        String result = Arrays.stream(input.split(""))
                .distinct()
                .collect(Collectors.joining());

        System.out.println(result);
    }
}

Output

progamin

📝 Explanation

In the Core Java approach, we use a LinkedHashSet, which stores only unique elements while preserving the insertion order. We iterate through each character in the string and add it to the set. Since duplicate values are automatically ignored, the set contains only unique characters. Finally, we build the resulting string using a StringBuilder.

In the Java 8 Stream approach, we split the string into individual characters using split(""). The distinct() method removes duplicate characters while maintaining their original order. Finally, Collectors.joining() combines all unique characters into a single string.


📊 Time Complexity

ApproachTime Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

📊 Space Complexity

ApproachSpace Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

💡 Interview Tip

If the interviewer asks you to preserve the original order, prefer using LinkedHashSet instead of HashSet. HashSet removes duplicates but does not guarantee insertion order.


Interview Question 5: Check Whether Two Strings are Anagrams

🟡 Difficulty: Medium

❓ Interview Question

How do you check whether two strings are anagrams in Java?


📖 Problem Statement

Two strings are called anagrams if they contain the same characters with the same frequency but arranged in a different order.

Write a Java program to check whether two given strings are anagrams.


📥 Example

Input

listen
silent

Output

Strings are Anagrams

Input

hello
world

Output

Strings are Not Anagrams

💻 Solution 1 – Core Java

import java.util.Arrays;

public class AnagramExample {

    public static void main(String[] args) {

        String str1 = "listen";
        String str2 = "silent";

        char[] ch1 = str1.toLowerCase().toCharArray();
        char[] ch2 = str2.toLowerCase().toCharArray();

        Arrays.sort(ch1);
        Arrays.sort(ch2);

        if (Arrays.equals(ch1, ch2)) {
            System.out.println("Strings are Anagrams");
        } else {
            System.out.println("Strings are Not Anagrams");
        }
    }
}

Output

Strings are Anagrams

🌊 Solution 2 – Java 8 Streams

import java.util.stream.Collectors;

public class AnagramStream {

    public static void main(String[] args) {

        String str1 = "listen";
        String str2 = "silent";

        String sortedStr1 = str1.chars()
                .sorted()
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());

        String sortedStr2 = str2.chars()
                .sorted()
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());

        if (sortedStr1.equals(sortedStr2)) {
            System.out.println("Strings are Anagrams");
        } else {
            System.out.println("Strings are Not Anagrams");
        }
    }
}

Output

Strings are Anagrams

📝 Explanation

The logic behind checking an anagram is simple. If two strings contain exactly the same characters with the same frequency, then after sorting their characters alphabetically, both strings become identical.

In the Core Java solution, we first convert both strings into character arrays using toCharArray(). We then sort the arrays using Arrays.sort() and compare them using Arrays.equals(). If both arrays are equal, the strings are anagrams.

In the Java 8 Stream solution, we convert each string into a stream of characters using chars(), sort them with sorted(), convert them back into strings, and compare the final sorted strings using equals().


📊 Time Complexity

ApproachTime Complexity
    Core Java    O(n log n)
Java 8 Streams    O(n log n)

📊 Space Complexity

ApproachSpace Complexity
    Core Java    O(n)
Java 8 Streams    O(n)

💡 Interview Tip

Before sorting, always check whether both strings have the same length. If their lengths differ, they cannot be anagrams, and you can return the result immediately without any additional processing. This small optimization is often appreciated in interviews.

Conclusion :

In this article, we explored five of the most commonly asked Java String coding interview questions, covering essential concepts such as reversing a string, checking for palindromes, counting vowels and consonants, removing duplicate characters, and verifying anagrams. For each problem, we discussed both the Core Java approach and a Java 8 solution (where applicable), along with the underlying logic and interview-focused tips.

These questions are frequently asked in Java Developer, Spring Boot Developer, and Java Full Stack Developer interviews because they assess your understanding of string manipulation, loops, collections, and problem-solving skills. While memorizing solutions can help, the real key to success is understanding the logic behind each approach and practicing the problems on your own.

Keep practicing these coding questions regularly and try implementing them without referring to the solutions. The more you practice, the more confident you'll become in technical interviews.

📝 Practice Challenge

Try solving the following problems on your own before checking the solutions:

  1. Reverse each word in a given sentence.
  2. Count the frequency of each character in a string.
  3. Find the first non-repeating character in a string.
  4. Check whether one string is a rotation of another string.
  5. Find the longest common prefix among a list of strings.

💡 Challenge Yourself: Try solving these problems using both Core Java and Java 8 Streams to strengthen your problem-solving skills and interview confidence.

🚀 Continue the Series

Ready for the next set of interview questions?

👉 Part 2: Top 5 Java Array Coding Interview Questions and Solutions (Core Java + Java 8)

https://sulochanabasavala.blogspot.com/2026/07/java-array-coding-interview-questions-part-2.html

In Part 2, you'll learn how to solve popular Java Array coding interview questions using both Core Java and Java 8 Streams. 

Happy Coding! 🚀 

Comments

Popular posts from this blog

React Basics – How to Create Component

How to Build REST API using Spring Boot (Step-by-Step Guide)

Spring Boot @RequestParam Annotation Explained with Real-Time Examples