Java String Interview Questions

Introduction

Without a doubt, the String class is the most used class in Java, representing a sequence of characters, treated as an object. Given the quintessential role of Strings in virtually all Java applications, recruiters give a lot of attention to String-related questions during a job interview. When going into an interview, a Java developer should have full and in-depth control and knowledge of this class.

Even better, you should also prepare for your interview by studying previous interview questions used by top companies, which you can do with Daily Coding Problem. With DCP, practice questions are emailed to you daily. Although, if you need to study Java Strings in particular, then read on.

Java String Interview Questions

Job interviews often discern two categories of questions - theoretical and coding:

Theoretical Questions

String Classes

Question

"What String classes are you familiar with?

Answer

This question can sound confusing at first but no worries - it's actually rather simple.

A string is a sequence of characters, and the String class isn't the only one that does that. There are three classes in Java which are used for creating String objects: String, StringBuffer and StringBuilder. This is actually a fairly in-depth topic when considering the differences between the classes and their advantages/disadvantages.

If you'd like to read more about these in detail, check out our article covering the topic - String vs StringBuilder vs StringBuffer.

String Immutability

Question

"Is String an immutable class, and if so, why?"

Answer

This is a very common question in interviews and a 'Yes' or 'No' answer usually doesn't cut it. You'll typically need to be able to explain more.

String is an immutable class. This means that once an instance of a String object is created, it cannot be modified. This is first and foremost the effect of the final modifier applied to the String class. Calling any sort of content-modifying method on a String instance will simply return a new, updated String instance - the original object doesn't change.

This can easily be observed in the source code of any String method:

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

The original str is never changed, because it can't be changed. Ultimately, the method returns a new String object.

String Pool

Question

"What is the String Pool?"

Answer

As mentioned, Strings are very commonly used. Leveraging the fact that they're immutable, the JVM saves all string literals in the Heap Memory. Each time we implicitly instantiate a String object, its literal value is compared to the ones in the Heap Memory and if it already exists, the reference variable is assigned to the already-existing memory location.

This approach can drastically save memory as there aren't any duplicate values. This collection of saved memory locations is called the String Pool.

String Inheritance

Question

"Can you extend String?"

Answer

Since String class is declared as final, it can't be inherited.

== vs .equals()

Question

"Is there any difference between the == operator and the .equals() method?"

Answer

Although they may appear the same, there's a distinct difference between these two equality validators:

  • The == operator checks for equality of reference variables and returns true if both point to the same object in memory.
  • The .equals() method is a method that compares two Strings based on their content and returns true if they're equal.

Using the == operator to compare Strings can return the expected result, due to the String Pool saving values in the same memory location, though oftentimes it won't.

On the other hand, .equals() will always return the expected result when comparing Strings.

Character Index

Question

"How do you find the value of a character at a specific position?"

Answer

The String class provides a method .charAt(int position) which returns a single character. Which character the method will return depends on the specified argument position.

Like in an array, 0 represents the first character's index in a String and .length() - 1 represents the last character's index.

String Concatenation

Question

"In what way can you perform String concatenation?"

Answer

Concatenation is an operation used to merge two Strings into a new one. Basic Strings can be concatenated simply by using the + operator or by using .concat() method, while StringBuffers and StringBuilders achieve concatenation by using .append() method.

When using the + operator with other data types, if possible, they're converted to a String.

Another way to join multiple Strings is by using the StringJoiner class:

// The delimeter is "", the prefix is "[" and the suffix is "+"
StringJoiner joiner = new StringJoiner("", "[", "+");
joiner.add("Orange")
  .add("Apple")
  .add("Pear");
  
System.out.println(joiner.toString());

The output would be:

[OrangeApplePear+

String Thread Safety

Question

"Are Strings thread-safe?"

Answer

In Java, every immutable object is thread-safe and therefore String is thread-safe too.

This applies to StringBuffer as well since it uses Java's synchronized keyword, but doesn't apply to StringBuilder, which isn't thread-safe since it is mutable and does not use the synchronized keyword.

String vs StringBuilder vs StringBuffer

Question

"What are the differences between the String, StringBuilder and StringBuffer classes?

Answer

String objects are easier to use, thread-safe, and immutable, which means they consume more memory and they are slower than their siblings (StringBuffer and StringBuilder) when it comes to string manipulation.

StringBuffer objects are mutable, memory efficient, and thread-safe, but they are still slow when compared to StringBuilder.

StringBuilder objects are also mutable, memory efficient, and extremely fast, but they are not thread-safe.

If you'd like to read more about Strings, StringBuffers, and StringBuilders, we've got a whole article that goes in-depth on the topic.

Coding Questions

Reversing a String

In order to reverse a String we would have to write a custom function right? Well, there is a workaround for this case - we can use StringBuilder or StringBuffer as a wrapper around our String object.

That way we can access the function .reverse() and use it to reverse our String without making a new custom function for the exact same task:

String str = "I'm a string waiting to be reversed";
System.out.println(str);

StringBuilder stringBuilder = new StringBuilder(str);
stringBuilder.reverse();
System.out.println("Reversing the string. . .\n");

System.out.println(stringBuilder.toString());

Output:

I'm a string waiting to be reversed
Reversing the string. . .

desrever eb ot gnitiaw gnirts a m'I

However, if the recruiter doesn't appreciate you using this workaround, there are many ways to reverse a String character by character. Let's list a couple:

1. Reversing by character array:

public String reverse(String str) {
    char[] characters = str.toCharArray();
    int start = 0;
    int finish = characters.length-1;
    char temp;
    
    while(finish > start) {
        temp = characters[start];
        characters[start] = characters[finish];
        characters[finish] = temp;
        finish--;
        start++;
    }
    return new String(in);
}

This approach is very efficient, as it simply rearranges the characters and returns a new String object with the array passed to the constructor.

2. Reversing by character stacking:

public String reverse(String str) {
    String result = "";
    for(int i = str.length() - 1; i >= 0; i--) {
        result = result + string.charAt(i);
    }
    System.out.println(result); 
}
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Although, this approach isn't as efficient due to creating a new String object via concatenation for each character.

Checking if String Contains Only Digits

The easiest approach to check if the String contains only digits is using the .matches() method and providing a String argument - "[0-9]+". The expected argument should be a regex (Regular Expression) to which the String is to be matched - in our case regex represents the numeric characters from 0 to 9!

String str = "09";
        
if (str.matches("[0-9]+")) {
    System.out.println("String contains only numbers.");
} else {
    System.out.println("String doesn't contain only numbers!");
}

Output:

String contains only numbers.

How to Convert a String to Integer

The Integer class provides three methods that allow us to covert Strings to Integers:

  • parseInt()
  • valueOf()
  • decode()

These are pretty straightforward, and return integers with a passed String:

String str = "1234";
int strNumber = Integer.parseInt(str);
int strNumber2 = Integer.valueOf(str);
int strNumber3 = Integer.decode(str);

System.out.println(4321 + strNumber);
System.out.println(4321 + strNumber);
System.out.println(4321 + strNumber);

Output:

5555
5555
5555

If you'd like to read all use-cases of these methods as well as their differences, we've got a great article on converting strings to integers that covers the topic in more detail.

Removing Duplicate Characters in a String

In order to remove duplicate characters in a String we can use either HashSets, Streams, and even LinkedLists. But for this particular example we are going to use only String objects and find the solution by implementing adequate logic.

First of all, we need two strings - one will contain the input String and the other one will contain the "filtered" result. After that we create a loop which should iterate through our input String, 1 character at a time.

We'll utilize a boolean flag, initially set to false. The inner loop iterates through the result String, comparing characters from the first String to the second:

  • If the character isn't present in the second String, we add it.
  • If the character is present in the second String, we mark the boolean flag as true which excludes the character from the concatenation

Here's the implementation:

String str = "stackabuse";
String str2 = "";
for (int i = 0; i < str.length(); i++) {
    boolean found = false;
    for (int j = 0; j < str2.length(); j++) {
        if (str.charAt(i) == str2.charAt(j)) {
            found = true;
            break;
        }
    }
    if (found == false) {
        str2 = str2.concat(String.valueOf(str.charAt(i)));
    }
}
System.out.println(str2);

Output:

stackbue

Finding the Maximum Occurring Character in a String

The best method for finding the maximum occurring character in a String is using HashMaps. In order to find the right character as well as the number of its occurrences, our HashMap should contain a char key and an int value.

The logic here is simple - check every character in a String and if a character already exists in a HashMap then increment it's value, else save the character in a HashMap and give it value of 1. For each character we are checking if its value is greater than the charCount variable which counts the maximum occurrence and if it is, we increment charCount.

At the end we iterate through the HashMap and search for a key which has charCount number of occurrences and when we find it we just print it. If there are multiple characters with the same charCount value they all get printed to the console:

public static void findMaxOccurrence(String input) {
    int charCount = 0;
    HashMap<Character, Integer> map = new HashMap<>();
    char[] inputChar = input.toCharArray();
    
    for (int i = 0; i < inputChar.length; i++) {
        char c = inputChar[i];
        
        if (map.containsKey(c)) {
            int count = map.get(c);
            count++;
            
            if (charCount < count) {
                charCount++;
            }
            
            map.put(c, count);
        } else {
            map.put(c, 1);
        }
    }

    Set set = map.keySet();
    Iterator<Character> iterator = set.iterator();
    while (iterator.hasNext()) {
        char key = iterator.next();
        
        if (map.get(key) == charCount) {
            System.out.println("Character '" + key + "' has the max occurrence: " + charCount + " times!");
        }
    }
}
    
public static void main(String[] args) {
    Main.findMaxOccurrence("This is the best example");
}

Output:

Character ' ' has the max occurrence: 4 times!
Character 'e' has the max occurrence: 4 times!

Find the First Non-Repeating Character in a String

So we need to find the first non-repeating character in a String, that means we must iterate through all characters of that String, compare them and as soon as we find the first non-repeating character we print it and the job is done.

This is easily done using a boolean flag and two loops. For each character, we iterate through the rest of the input String. If the character from the first loop matches any of the characters in the second loop, the flag is set to true.

If the flag is false, which means that we didn't find at least two occurrences of the same character, we break and print out the character:

String str = "stackabuse";
for (int i = 0; i < str.length(); i++) {
    boolean found = false;
    for (int j = 0; j < str.length(); j++) {
        if (i != j) {
            if (str.charAt(i) == str.charAt(j)) {
                found = true;
            }
        }
    }
    if (!found) {
        System.out.println("The first non-repeating character is: '" + str.charAt(i) + "'");
        break;
    } else if (found && i == str.length() - 1) {
        System.out.println("There is no non-repeating character in this string!");
    }
}

Output:

The first non-repeating character is: 't'

Checking if Two Strings are Anagrams of Each Other

For this question we will be creating a custom method that checks if two given Strings are anagrams and returns an appropriate boolean value.

Firstly, we modify our two Strings by removing all the white space they might have. After they are trimmed, we compare their length - if they don't have the same length there is no possibility that they can be anagrams of one another, so if that's the case we return false.

Otherwise we transform our Strings to character arrays and turn their content to lower-case letters. Finally, Arrays.sort() is called for both Strings and it sorts the characters by alphabetical order and we return the result of a function Arrays.equals() which compares two character arrays and returns true if they have the same characters:

public static boolean checkAnagram(String str, String str2) {
    str = str.replaceAll("\\s", "");
    str2 = str2.replaceAll("\\s", "");

    if (str.length() != str2.length()) {
        return false;
    } else {
        char[] strCharArray = str.toLowerCase().toCharArray();
        char[] strCharArray2 = str2.toLowerCase().toCharArray();

        Arrays.sort(strCharArray);
        Arrays.sort(strCharArray);

        return (Arrays.equals(strCharArray, strCharArray));
    }
}
    
public static void main(String[] args) {
    String str = "stackabuse";
    String str2 = "Backseat Us";

    if (checkAnagram(str, str2)) {
        System.out.println(str + " and " + str2 + " are Anagrams!");
    } else {
        System.out.println(str + " and " + str2 + " are not Anagrams!");
    }
}

Output:

stackabuse and Backseat Us are Anagrams!

Counting the Number of Words in a String

To accomplish this we should divide our String in smaller pieces (words) and use a space character as a delimiter:

String str = "Java is an awesome programming language!";
str = str.trim().replaceAll("\\s{2,}", " ");
String splitStr[] = str.split(" ");
System.out.println("The provided string '" + str + "' contains " + splitStr.length + " words!");

Output:

The provided string 'Java is an awesome programming language!' contains 6 words!

Conclusion

In this article, we've covered the common interview questions related to Strings.

If you're interested in reading more about Programming Interview Questions in general, we've compiled a lengthy list of these questions, including their explanations, implementations, visual representations, and applications.

We also highly recommend checking out Daily Coding Problem is you're serious about improving your ability to solve programming questions that are actually asked by top tech companies.

Last Updated: August 23rd, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms