Interview

15 Java String Interview Questions and Answers

Prepare for your Java interview with our guide on Java String operations and concepts, featuring common and advanced questions.

Java String is a fundamental class in the Java programming language, essential for handling and manipulating text. Strings in Java are immutable, meaning once created, their values cannot be changed, which ensures thread safety and performance optimization. Mastery of Java String operations is crucial for tasks ranging from basic text processing to complex data manipulation in enterprise-level applications.

This article provides a curated selection of interview questions focused on Java String. Reviewing these questions will help you deepen your understanding of Java String operations and concepts, enhancing your ability to tackle technical challenges and demonstrate your expertise in interviews.

Java String Interview Questions and Answers

1. Explain the immutability of Strings and its implications.

In Java, Strings are immutable, meaning once a String object is created, it cannot be changed. Any modification results in a new String object. This immutability is achieved by making the String class final and its fields private and final.

Implications of String immutability:

  • Performance: Immutability allows for the use of the String pool, optimizing memory by storing only one copy of each literal String, reducing memory overhead.
  • Security: Immutability ensures that sensitive data like passwords cannot be altered once created, preventing accidental or malicious modifications.
  • Thread Safety: Immutable objects are inherently thread-safe, eliminating the need for synchronization when Strings are shared between threads.

Example:

String str1 = "Hello";
String str2 = str1.concat(" World");

System.out.println(str1); // Outputs "Hello"
System.out.println(str2); // Outputs "Hello World"

In this example, the original String str1 remains unchanged after the concat operation, demonstrating its immutability.

2. How does the StringBuilder class differ from the String class?

The String class in Java is immutable, leading to performance issues when performing numerous string manipulations, as it creates many temporary objects. The StringBuilder class is mutable, allowing modifications without creating new objects, making it more efficient for frequent string manipulations.

Example:

// Using String
String str = "Hello";
str += " World";
str += "!";

// Using StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.append("!");

3. What is the significance of the intern() method?

The intern() method in Java returns a canonical representation for the string object. If the pool already contains a string equal to this String object, the string from the pool is returned. Otherwise, this String object is added to the pool.

Example:

public class StringInternExample {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = "Hello";
        
        // Before interning
        System.out.println(str1 == str2); // Output: false
        
        // After interning
        str1 = str1.intern();
        System.out.println(str1 == str2); // Output: true
    }
}

In this example, str1 is initially not interned. After calling str1.intern(), str1 refers to the same memory location as str2.

4. Describe how the substring() method works and any potential pitfalls.

The substring() method extracts a part of a string based on specified indices. It has two forms:

  • substring(int beginIndex): Returns a new string from beginIndex to the end.
  • substring(int beginIndex, int endIndex): Returns a new string from beginIndex to endIndex - 1.

Example:

public class SubstringExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String subStr1 = str.substring(7); // "World!"
        String subStr2 = str.substring(0, 5); // "Hello"
        
        System.out.println(subStr1);
        System.out.println(subStr2);
    }
}

Potential pitfalls include:

  • IndexOutOfBoundsException: Thrown if beginIndex is negative, or endIndex is larger than the string length, or beginIndex is greater than endIndex.
  • Memory Leaks in Older Java Versions: In versions prior to Java 7u6, substring() could cause memory leaks by retaining a reference to the original string.

5. Write a method to find the first non-repeated character in a String.

To find the first non-repeated character in a string, use a hash map to store character frequencies. Iterate through the string twice: first to populate the map, then to find the first character with a count of one.

Example:

import java.util.LinkedHashMap;
import java.util.Map;

public class FirstNonRepeatedCharacter {
    public static Character findFirstNonRepeatedChar(String str) {
        Map<Character, Integer> charCountMap = new LinkedHashMap<>();

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

        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }

        return null;
    }

    public static void main(String[] args) {
        String str = "swiss";
        System.out.println(findFirstNonRepeatedChar(str)); // Output: w
    }
}

6. Explain the difference between == and equals() when comparing Strings.

In Java, == is a reference comparison operator, checking if two references point to the same object. equals() compares the content of two String objects.

Example:

String str1 = new String("Hello");
String str2 = new String("Hello");

System.out.println(str1 == str2); // false
System.out.println(str1.equals(str2)); // true

In this example, str1 == str2 returns false because they are different objects, but str1.equals(str2) returns true because their content is the same.

7. Write a method to convert a given String to title case (first letter of each word capitalized).

To convert a string to title case, capitalize the first letter of each word and convert the rest to lowercase. Split the string into words, process each word, and join them back together.

Example:

public class TitleCaseConverter {
    public static String toTitleCase(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }

        String[] words = input.split("\\s+");
        StringBuilder titleCase = new StringBuilder();

        for (String word : words) {
            if (word.length() > 0) {
                titleCase.append(Character.toUpperCase(word.charAt(0)))
                         .append(word.substring(1).toLowerCase())
                         .append(" ");
            }
        }

        return titleCase.toString().trim();
    }

    public static void main(String[] args) {
        String input = "this is a sample string";
        System.out.println(toTitleCase(input)); // Output: "This Is A Sample String"
    }
}

8. What are the performance implications of using + operator for String concatenation in loops?

Using the + operator for String concatenation in loops can lead to performance issues due to the creation of new String objects. A more efficient approach is to use StringBuilder or StringBuffer, which are mutable and provide an append method.

Example:

public class StringConcatenation {
    public static void main(String[] args) {
        // Inefficient way using + operator
        String result = "";
        for (int i = 0; i < 1000; i++) {
            result += "text";
        }

        // Efficient way using StringBuilder
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            sb.append("text");
        }
        String efficientResult = sb.toString();
    }
}

9. Write a method to find the longest substring without repeating characters.

To find the longest substring without repeating characters, use the sliding window technique. Maintain a window that expands and contracts as you traverse the string, ensuring no characters within the window are repeated.

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

public class LongestSubstring {
    public static int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int maxLength = 0;
        int left = 0, right = 0;
        Set<Character> set = new HashSet<>();

        while (right < n) {
            if (!set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                right++;
                maxLength = Math.max(maxLength, right - left);
            } else {
                set.remove(s.charAt(left));
                left++;
            }
        }
        return maxLength;
    }

    public static void main(String[] args) {
        String s = "abcabcbb";
        System.out.println(lengthOfLongestSubstring(s)); // Output: 3
    }
}

10. Explain how the replaceAll() method works and provide an example use case.

The replaceAll() method takes a regular expression and a replacement string, scanning the string for substrings that match the regex and replacing them with the specified replacement.

Example:

public class ReplaceAllExample {
    public static void main(String[] args) {
        String text = "The rain in Spain stays mainly in the plain.";
        String modifiedText = text.replaceAll("ain", "XYZ");
        System.out.println(modifiedText);
    }
}

In this example, replaceAll() replaces all occurrences of “ain” with “XYZ”. The output will be:

The rXYZ in SpXYZ stays mXYZly in the plXYZ.

11. Write a method to check if two Strings are anagrams of each other.

To check if two strings are anagrams, ensure both contain the same characters with the same frequency. One way is by sorting both strings and comparing them.

Example:

import java.util.Arrays;

public class AnagramChecker {
    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }
        
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();
        
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);
        
        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("listen", "silent")); // true
        System.out.println(areAnagrams("hello", "world"));   // false
    }
}

12. Explain the concept of String interning and its benefits.

String interning in Java stores only one copy of each distinct string value. The String class maintains a pool of strings. When a new string is created, the JVM checks the pool for an identical string. If found, the reference to the existing string is returned, saving memory.

Example:

public class StringInternExample {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = new String("hello").intern();

        System.out.println(s1 == s2); // true
        System.out.println(s1 == s3); // true
    }
}

In this example, s1 and s2 refer to the same string in the pool. The intern() method on s3 ensures it also refers to the same string.

13. Write a method to find the longest palindromic substring in a given String.

To find the longest palindromic substring, use the expand around the center technique. This approach is intuitive and easy to implement.

Example:

public class LongestPalindrome {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) return "";
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private int expandAroundCenter(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }
}

14. Compare the performance implications of using String, StringBuilder, and StringBuffer for concatenation.

When concatenating strings, the choice between String, StringBuilder, and StringBuffer affects performance.

  • String: Immutable, creating a new object for each concatenation, leading to overhead.
  • StringBuilder: Mutable and not synchronized, making it faster for concatenation when thread safety is not a concern.
  • StringBuffer: Similar to StringBuilder, but synchronized, making it thread-safe with a performance cost.

Example:

public class StringConcatenation {
    public static void main(String[] args) {
        // Using String
        String str = "Hello";
        for (int i = 0; i < 1000; i++) {
            str += " World";
        }

        // Using StringBuilder
        StringBuilder sb = new StringBuilder("Hello");
        for (int i = 0; i < 1000; i++) {
            sb.append(" World");
        }

        // Using StringBuffer
        StringBuffer sbf = new StringBuffer("Hello");
        for (int i = 0; i < 1000; i++) {
            sbf.append(" World");
        }
    }
}

15. How can you use regular expressions with Strings? Provide an example.

Regular expressions (regex) in Java are used for pattern matching within strings. The java.util.regex package provides classes like Pattern and Matcher.

Example:

import java.util.regex.*;

public class RegexExample {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog.";
        String patternString = "\\b\\w{4}\\b"; // Matches words with exactly 4 letters

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println("Found: " + matcher.group());
        }
    }
}

In this example, the regex pattern \\b\\w{4}\\b finds words with exactly four letters in the text.

Previous

10 Computer Science Fundamentals Interview Questions and Answers

Back to Interview
Next

10 SAP CRM Interview Questions and Answers