Java String Interview Questions

The given Java String interview questions range from string methods, string immutability and memory leak issues to simple examples and usecases. I will try to cover the most asked questions in Java interviews.

1. Is String a Keyword in Java?

No. String is not a reserved keyword in Java. It is a derived data type, i.e., it is a class.

public class StringExample
{
    public static void main(String[] args)
    {
        Integer String = 10;

        System.out.println(String);		//Prints 10
    }
}

2. Why are Strings Immutable?

We all know that strings in Java are immutable. If you want to know what immutability is and how it is achieved? Follow this post: How to make a java class immutable?

Here the question is WHY? Why immutable? Let’s analyze.

  • The very first reason is performance improvement. Java language was developed to speed up application development as it was not that much fast in previous languages. JVM designers must have been smart enough to identify that real-world applications will consist mostly of Strings in the form of labels, messages, configuration, output and other forms. Seeing such overuse, they imagined how dangerous string’s improper use could be. So they came up with the concept of a String pool. A string pool is nothing but a collection of mostly unique strings. The very basic idea behind the String pool is to reuse string once created. This way, if a particular string is created 20 times in code, the application has only one instance.
  • The second reason I see as security considerations. Strings are the most used parameter type in each aspect of java programming. Be it loading a driver or opening a URL connection, you need to pass the information as a parameter in the form of a string. If strings have not been final, they have opened up Pandora’s box of security issues.

3. What is String Constant Pool?

The string pool is a particular memory area in regular heap memory where these string constants are stored. These constants are referred by the string variables during the life cycle of the application.

In Java, we can create a string in many ways. For example, using the string literals and using the new keyword.

String str1 = "abc";

String str2 = new String("abc");

Using string literal causes JVM to verify if there is already a string “abc” (same char sequence). If such string exists, JVM assigns the reference of the existing object to variable str; otherwise, a new object “abc” will be created, and its reference will be assigned to the variable str1.

When using new keyword, Java creates a new String object in the normal heap memory. We must intern a string to move from heap memory to string pool.

To have better memory utilization and overall performance, using the string literals to create the strings is recommended. Unless an explicit copy of the original is needed, the use of the constructor is unnecessary since Strings are immutable.

4. What is String intern()?

When the String intern() is invoked if the string pool already contains a string with the same content as this string (determined by the equals()), then the reference from the pool is returned. Otherwise, this String object is added to the pool and a reference to this new String object in the pool is returned.

In simple words, string interning is the process of moving a String object from regular heap memory to String constant and using the object reference from the pool.

String str = new String("abc");

str.intern();

For the intern() method, for any two strings s1 and s2, s1.intern() == t2.intern() is true if and only if s1.equals(s2) is true.

This means if s1 and s2 are different string objects and have the same character sequence, then calling intern() on both will result in a single string pool literal referred by both variables.

By default, remember that all literal strings and string-valued constant expressions are interned.

5. How to Find Matching Strings with Regular Expressions?

We can use Pattern and Matcher API for regular expression matching. String class provides its own method matches(). We should be using the matches() directly. This method also uses Pattern.matches() inside the function definition.

String str = new String("Welcome to howtodoinjava.com");
 
System.out.println(str.matches("(.*)java(.*)"));    //Prints true
System.out.println(Str.matches("(.*)python(.*)"));  //Print false

6. How to Compare Two Strings?

Another favorite area in interviews. There are generally two ways to compare objects

  • Using == operator
  • Using equals() method

The == operator compare for object references. So if two string objects are referring to the same literal in the string pool or the same string object in the heap then ‘s == t‘ will return true, else false.

The equals() method is overridden in String class and verifies the char sequences held by String objects. In other words, equals() method compares the values of string objects. If they store the same char sequence, the ;s.equals(t); will return true, else false.

7. How do Strings work in Java?

Like any other programming language, String in Java is a sequence of characters. This is more like a utility class to work on that char sequence. This char sequence is maintained in the following variable of type char array:

/** The value is used for character storage. */
private final char value[];

Various string methods operate on this array in different scenarios using the following variables to maintain the position in the array:

/** The offset is the first index of the storage that is used. */
private final int offset;
 
/** The count is the number of characters in the String. */
private final int count;

8. How to Check a Palindrome String?

A String is Palindrome if its value is the same when reversed. To check Palindrome, reverse the string and compare it with the original string.

If the original strings and reversed strings are the same, then the given string is a palindrome.

String originalString = "abcdcba";
         
StringBuilder strBuilder = new StringBuilder(originalString);
String reverseString = strBuilder.reverse().toString();

 
boolean isPalindrame = originalString.equals(reverseString);

System.out.println(isPalindrame);    //true

9. How to Remove or Replace Characters in a String?

To replace or remove characters, use String.replace() or String.replaceAll().

Both methods take two arguments. The first argument is a character to be replaced, and the second argument is a new character placed in the string.

If you want to remove characters, pass blank characters in the second argument.

String originalString = "howtodoinjava";

//Replace one character
System.out.println( originalString.replace("h", "H") );         //Howtodoinjava

//Replace all matching characters
System.out.println( originalString.replaceAll("o", "O") );      //hOwtOdOinjava

//Remove one character
System.out.println( originalString.replace("h", "") );         //owtodoinjava

//Remove all matching characters
System.out.println( originalString.replace("o", "") );         //hwtdinjava

10. How to convert a String Uppercase or Lowercase?

Use String.toLowerCase() and String.toUpperCase() methods to convert strings to lowercase or uppercase.

String blogName = "HowToDoInJava.com";

System.out.println(blogName.toLowerCase());     //howtodoinjava.com

System.out.println(blogName.toUpperCase());     //HOWTODOINJAVA.COM

11. Can we use String in ‘switch‘ Statements?

Yes, we can use String class in switch statements since Java 7. Before Java 7, it was impossible, and we had to use if-else statements to achieve similar behavior.

String number = "1";

switch (number)
{
case "1":
    System.out.println("One");	//Prints '1'
    break;
case "2":
    System.out.println("Two");
    break;
default:
    System.out.println("Other");
}

12. How to Print all Permutations of a String?

A permutation is a re-arrangement of the elements of characters so that each arrangement is unique with respect to other arrangements. e.g., below are the permutations of string “ABC” – ABC ACB BAC BCA CBA CAB.

A string of length N has N! (N Factorial) permutations.

import java.util.HashSet;
import java.util.Set;
 
public class StringExample 
{
    public static void main(String[] args) 
    {
        System.out.println(getPermutations("ABC")); 
 
        //Prints
        //[ACB, BCA, ABC, CBA, BAC, CAB]
    }
 
    public static Set<String> getPermutations(String string) 
    {
        //All permutations
        Set<String> permutationsSet = new HashSet<String>();
         
        // invalid strings
        if (string == null || string.length() == 0) 
        {
            permutationsSet.add("");
        } 
        else
        {
            //First character in String
            char initial = string.charAt(0); 
             
            //Full string without first character
            String rem = string.substring(1); 
             
            //Recursive call
            Set<String> wordSet = getPermutations(rem);
             
            for (String word : wordSet) {
                for (int i = 0; i <= word.length(); i++) {
                    permutationsSet.add(charInsertAt(word, initial, i));
                }
            }
        }
        return permutationsSet;
    }
 
    public static String charInsertAt(String str, char c, int position) 
    {
        String begin = str.substring(0, position);
        String end = str.substring(position);
        return begin + c + end;
    }
}

13. How to Reverse Each Word of a String?

To reverse each word separately, tokenize the string and get all words separated in an array. Then, apply reverse word logic to each word, and finally, concatenate all words.

String blogName = "how to do in java dot com";
 
//spilt on white space
String[] tokens = blogName.split(" ");
 
//It will store reversed words 
StringBuffer finalString = new StringBuffer();
 
//Loop all words and reverse them
for (String token : tokens) {
    String reversed = new StringBuffer(token).reverse().toString();
    finalString.append(reversed);
    finalString.append(" ");
}
 
//Check final string
System.out.println(finalString.toString());     //woh ot od ni avaj tod moc

14. How to Split a String?

Use String.split() method that breaks a given string around matches of the given regular expression. It’s also called get string tokens based on a delimiter.

The split() method returns the array of strings. Each string in the array is an individual token.

String numbers = "1,2,3,4,5,6,7";
         
String[] numArray = numbers.split(",");
 
System.out.println(Arrays.toString(numArray));  //[1, 2, 3, 4, 5, 6, 7]

15. Why should We not Use Strings for Storing Passwords?

We know that strings are stored in the constant pool in Java. Once a string is created in the string pool, it stays in the pool unless it is garbage collected. By this time, any malicious program can access the memory area in the physical memory and access the string data as well.

If we store the password as a string, it will be held in the spring pool and available in memory for a longer duration than required because garbage collection cycles are unpredictable. This makes sensitive password strings vulnerable to hacking and data theft.

Can one option be argued to make String blank after using it? No, we cannot. We know that once a String is created, we cannot manipulate it e.g. you cannot change its content. Strings are final and immutable.

But char arrays are mutable, we can overwrite their content after using it. So our application shall use char[] to store password text, and after using the password, replace the array content with a blank.

String password = "123456";     //Do not use it
         
char[] passwordChars = new char[4];      //Get password from some system such as database
 
//use password
 
for(char c : passwordChars) {
    c = ' ';
}

16. Are Strings Thread-safe?

Yes, strings are thread-safe because they are immutable.

Remember that all immutable instances are thread-safe, by design.

17. Why is String a Great Fit HashMap Keys?

In Java, a Map key shall be immutable and should honor the contract between equals() and hashCode() method. String class satisfies both conditions.

Also, the String class provides many useful methods to compare, sort, tokenize or lower-upper cases. These methods can be used while performing CRUD operations on Map.

All this makes String a very useful class to use in Map rather than creating our own class.

18. What is the Difference between String, StringBuffer and StringBuilder?

  • String class represents a sequence of characters and provides useful methods to work with characters. String class instances are immutable. So each time we perform string concatenation using string class, a new object will be created with the concatenated string.
  • StringBuilder class is used to perform string concatenation operations in a more memory-efficient way. It internally maintains char[] and manipulates the content in this array only. When we need to get the complete concatenated string after performing all operations, it creates a new String with the stored character array.
  • StringBuffer is very much same as StringBuilder class. The only difference is that it is thread-safe. It’s all methods are synchronized.

19. How to Concatenate Multiple Strings?

Use StringBuffer or StringBuilder classes based on whether you need thread safety or not. Use append() methods in both classes to concatenate strings.

StringBuffer buffer = new StringBuffer();
         
buffer.append("how")
        .append("to")
        .append("do")
        .append("in")
        .append("java")
        .append(".")
        .append("com");
 
String blogName = buffer.toString();
 
System.out.println(blogName); //howtodoinjava.com

20. Count the Number of String Objects in Given Program?

String s1 = "howtodoinjava.com";
String s2 = "howtodoinjava.com";
String s3 = new String("howtodoinjava.com");
  • Above code will create 2 objects.
  • The first statement will create the first string literal in the string pool.
  • The second statement will not create any new object and s2 will refer to the same string constant as s1.
  • The third statement will create a new string object in heap memory.

21. Count the Occurrences of Each Character in a String?

To find the number of occurrences of each character in a given string, we have used HashMap with the character as a key and its occurrence count as a value.

With each new occurrence of a character, we will increment the counter value for that character.

String blogName = "howtodoinjava.com";
 
HashMap<Character, Integer> occurancesMap = new HashMap<Character, Integer>();
 
char[] strArray = blogName.toCharArray();
 
for (char c : strArray)
{
    if(occurancesMap.containsKey(c))
    {
        occurancesMap.put(c, occurancesMap.get(c)+1);
    }
    else
    {
        occurancesMap.put(c, 1);
    }
}
 
System.out.println(occurancesMap);
//{a=2, c=1, d=1, h=1, i=1, j=1, m=1, n=1, .=1, o=4, t=1, v=1, w=1}

22. Reverse a String without StringBuilder or StringBuffer?

The best way to reverse a string is the StringBuffer.reverse() and StringBuilder.reverse() methods. Still, the interviewer may ask you to write your own program, to check your skill level.

Use the below-given recursion-based example to reverse the string.

This program takes the first character from the string and places it at the last position in the string. It uses this replacement for all characters in the string until the whole string is reversed.

public class StringExample
{
    public static void main(String[] args) 
    {
        String blogName = "howtodoinjava.com";
         
        String reverseString = recursiveSwap(blogName);
         
        System.out.println(reverseString);
    }
     
    static String recursiveSwap(String str)
    {
         if ((null == str) || (str.length() <= 1))
         {
                return str;
         }
         return recursiveSwap(str.substring(1)) + str.charAt(0);
    }
}

I think these frequently asked String interview questions will help you in your next interview. If you know any more questions specifically regarding String class, please share.

Happy Learning !!

Comments

Subscribe
Notify of
guest
31 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode