Skip to main content

Top 15 Java String Coding Interview Questions – Part 2

Java String Coding Questions – Part 2

Top 15 Java String Coding Interview Questions – Part 2


1. Reverse a String Using Recursion

public class ReverseRecursively {
    public static String reverse(String str) {
        if (str.isEmpty()) return str;
        return reverse(str.substring(1)) + str.charAt(0);
    }

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

2. Find All Permutations of a String

public class StringPermutations {
    public static void permute(String str, String ans) {
        if (str.length() == 0) {
            System.out.println(ans);
            return;
        }
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            String ros = str.substring(0, i) + str.substring(i + 1);
            permute(ros, ans + ch);
        }
    }

    public static void main(String[] args) {
        permute("abc", "");
    }
}

3. Count Words in a String

public class WordCount {
    public static void main(String[] args) {
        String str = "Java is platform independent";
        String[] words = str.trim().split("\\s+");
        System.out.println("Word Count: " + words.length);
    }
}

4. Check if String is Rotation of Another

public class StringRotation {
    public static void main(String[] args) {
        String s1 = "ABCD";
        String s2 = "CDAB";
        boolean result = (s1.length() == s2.length()) && ((s1 + s1).contains(s2));
        System.out.println("Is Rotation: " + result);
    }
}

5. Count the Number of Alphabets, Digits and Special Characters

public class CountAllTypes {
    public static void main(String[] args) {
        String str = "Java123@#";
        int letters = 0, digits = 0, special = 0;

        for (char c : str.toCharArray()) {
            if (Character.isLetter(c)) letters++;
            else if (Character.isDigit(c)) digits++;
            else special++;
        }

        System.out.println("Letters: " + letters);
        System.out.println("Digits: " + digits);
        System.out.println("Special: " + special);
    }
}

6. Find the Most Frequent Character

import java.util.HashMap;

public class MostFrequentChar {
    public static void main(String[] args) {
        String str = "success";
        HashMap<Character, Integer> map = new HashMap<>();

        for (char c : str.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        char maxChar = ' ';
        int max = 0;
        for (char c : map.keySet()) {
            if (map.get(c) > max) {
                max = map.get(c);
                maxChar = c;
            }
        }

        System.out.println("Most Frequent: " + maxChar);
    }
}

7. Convert Char Array to String

public class CharArrayToString {
    public static void main(String[] args) {
        char[] arr = {'J', 'a', 'v', 'a'};
        String str = new String(arr);
        System.out.println(str);
    }
}

8. Remove All Whitespaces From String

public class RemoveSpaces {
    public static void main(String[] args) {
        String str = "  Java  Developer ";
        System.out.println(str.replaceAll("\\s", ""));
    }
}

9. Replace Each Vowel with '*' in String

public class ReplaceVowels {
    public static void main(String[] args) {
        String str = "interview";
        str = str.replaceAll("[aeiouAEIOU]", "*");
        System.out.println(str);
    }
}

10. Capitalize First Letter of Each Word

public class CapitalizeWords {
    public static void main(String[] args) {
        String[] words = "java interview questions".split(" ");
        StringBuilder sb = new StringBuilder();
        for (String w : words) {
            sb.append(Character.toUpperCase(w.charAt(0)))
              .append(w.substring(1)).append(" ");
        }
        System.out.println(sb.toString().trim());
    }
}

11. Remove All Digits from String

public class RemoveDigits {
    public static void main(String[] args) {
        String str = "Java123Code456";
        System.out.println(str.replaceAll("\\d", ""));
    }
}

12. Toggle Case of Each Character

public class ToggleCase {
    public static void main(String[] args) {
        String str = "Java123";
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (Character.isUpperCase(c))
                sb.append(Character.toLowerCase(c));
            else if (Character.isLowerCase(c))
                sb.append(Character.toUpperCase(c));
            else
                sb.append(c);
        }
        System.out.println(sb.toString());
    }
}

13. Check if a String is Numeric

public class IsNumeric {
    public static void main(String[] args) {
        String input = "12345";
        boolean result = input.matches("\\\\d+");
        System.out.println("Is Numeric: " + result);
    }
}

14. Count Occurrence of a Given Word

public class WordOccurrence {
    public static void main(String[] args) {
        String str = "Java is awesome. Java is powerful.";
        String word = "Java";
        int count = str.split(word, -1).length - 1;
        System.out.println("Count: " + count);
    }
}

15. Find the Longest Palindromic Substring

public class LongestPalindrome {
    public static void main(String[] args) {
        String str = "abaxyzzyxf";
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j <= str.length(); j++) {
                String sub = str.substring(i, j);
                if (isPalindrome(sub) && sub.length() > result.length()) {
                    result = sub;
                }
            }
        }
        System.out.println("Longest Palindrome: " + result);
    }

    public static boolean isPalindrome(String s) {
        return s.equals(new StringBuilder(s).reverse().toString());
    }
}

Conclusion

Yeh 15 naye string coding questions interview ke liye important aur unique level ke hain. Inhe bar-bar practice karo taaki logic dimaag mein fit ho jaye.

Don’t forget to check Part-1: Java String Coding Questions – Part 1

For more real interview prep, stay connected with InterviewYatra.com

Comments

Popular posts from this blog

Top 15 React Interview Questions for 1–2 Years Experience

🟦 Top 15 React Interview Questions for 1–2 Years Experience Preparing for a React interview with 1–2 years of experience? Here's a carefully curated list of 15 important React questions with clear, real-world answers. These are frequently asked in interviews at companies like TCS, Infosys, Cognizant, Capgemini, and product-based firms. Q1. What is the Virtual DOM in React, and how does it improve performance? Answer: The Virtual DOM is a lightweight, in-memory copy of the real DOM. When state/props change, React creates a new Virtual DOM tree, compares it with the old one (diffing), and only updates the parts of the real DOM that changed. This makes rendering much faster and improves performance in large applications. Q2. What is JSX in React? Answer: JSX stands for JavaScript XML. It allows us to write HTML elements in JavaScript and place them in the DOM without using createElement() . JSX improves code readability and is transpiled to React.createElement() calls. ...

Top 15 Spring Boot Interview Questions and Answers – Real Examples (2025)

Top 15 Spring Boot Interview Questions – 2025 Spring Boot is one of the most demanded frameworks for Java backend development. Whether you're interviewing for TCS, Infosys, or a product-based company, these Spring Boot questions will help you prepare like a pro. Here are 15 questions with detailed explanations for developers with 1–2 years of experience. Q1. What is Spring Boot? Answer: Spring Boot is a Java-based open-source framework built on top of the Spring Framework. It helps developers create stand-alone, production-ready Spring applications with minimal configuration. Its key features include: Auto-configuration Embedded servers (Tomcat, Jetty) Starter dependencies Production-ready tools (Actuator, Metrics, etc.) Example: You can create a REST API within minutes by using @RestController and spring-boot-starter-web — no need for external web server deployment. Q2. What is the role of @SpringBootApplication annotation? Answer: This annotation i...

Wipro Java Developer Interview Questions with Answers (Mid-Level Role)

  Wipro Java Developer Interview Questions with Answers (Mid-Level Role) (Glassdoor Based – May 2024) Interview Location: Bengaluru Interview Mode: Online Candidate Role: Mid-Level Java Developer Source: Based on real experience shared on Glassdoor Review Summary: Easy and conversational. Interviewer was friendly. Focus was mainly on Java basics, internals, and real-world understanding. Q1: What is static in public static void main(String[] args) ? A: The static keyword lets the JVM call the method without creating an object. It indicates that the method belongs to the class, not instances. Q2: Why does a Java program start from the main method? A: main() is the predefined entry point of a Java application. The JVM starts execution from there. Q3: What are Checked and Unchecked Exceptions? With examples. A: Checked Exceptions : Detected at compile time. E.g., IOException , SQLException . Unchecked Exceptions : Detected at runtime. E.g., NullPointerExce...