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

TCS Java Interview | Java | Spring Boot | Microservices | Database

TCS Java Interview | Java | Spring Boot | Microservices | Database This post is based on a Java backend developer interview simulation and provides direct transcript-based answers to help you prepare for similar interviews. 📺 This interview scenario was inspired by a video from the  YouTube channel:  CloudTech . 🔗 Watch the full video here:  https://www.youtube.com/watch?v=yVj2EgwZxk4 1. Can you introduce yourself and talk about your tech stack and domains? I have around 4.5 years of experience working as a Java developer. My core expertise is in Java and developing REST APIs using Spring Boot. I also have basic knowledge of microservices architecture. On the database side, I work with SQL and Oracle. Additionally, I have exposure to UI technologies like Angular, HTML, and CSS, but they are secondary skills. My primary focus is backend Java development. 2. Which version of Java are you currently working on? We are currently using Java 8 but are in the process of upgr...

Top 20 Spring Boot Microservices Architecture Interview Questions (With Speakable Answers)

Top 20 Spring Boot Microservices Architecture Interview Questions (With Speakable Answers) * * * 1. What is Microservices Architecture?   → Microservices architecture breaks an application into small, independent services. Each one handles a specific business function and can be developed, deployed, and scaled independently. They usually communicate over REST APIs or messaging queues. * * * 2. How does Spring Boot help in building microservices?   → Spring Boot offers embedded servers, auto-configuration, starter templates, and production-ready tools. It works well with Spring Cloud to provide service discovery, config management, load balancing, and more. * * * 3. What are the core components in a microservices setup?   → Key components include:   ✓ API Gateway   ✓ Eureka (Service Discovery)   ✓ Config Server   ✓ Kafka or RabbitMQ   ✓ Circuit Breaker (like Resilience4j)   ✓ Centralized logging and monitoring (ELK, Prometheus) * * * 4. What i...

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...