30 Java String Interview Questions

30 Java String Interview Questions
30 Java String Interview Questions

Introduction

Java is the most popular programming language among developers. Even after new programming languages are developing, JAVA seems to get more widespread year on year. One of the reasons behind this is its platform independence. Programs can run on different computers as long as the Java runtime environment is installed.

This is the reason why JAVA is a favorite among interviewers. Sometimes, interviewers focus mainly on String data structure. But string interview questions are in itself so vast that you won’t be able to focus on other concepts. 

With the little time you had while preparing for your interviews, you can go through the string interview questions covered in this blog which can help you in your upcoming interviews.

The blog is divided into Intermediate level string interview questions and Advanced level String Interview Questions so that you can have a clearer understanding.

Intermediate Level String Interview Questions

Q1. What are the different ways to create string objects?

 String objects can be created in two ways:

  1. Using the ‘new’ operator.
  2. Using double-quotes. 

Several constructors are also available in the String class to create strings from a char array, byte array, StringBuilder, and StringBuffer.

String S = new String("coding ninjas"); // using new operator.
String S = "coding ninjas"; // using double quotes.

When the String is created with the double quotes, JVM searches it for in the string pool; if the same value is found, it returns the reference to that String else creates a new object with the new value provided.

In the other case, if the String is created with the ‘new’ operator, then JVM creates a new object but not in the string pool. If we want to create the object in the string pool, we can use the intern() method.

Q2. Difference between String, StringBuffer, and StringBuilder in java

blog banner 1

There are three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. 

StringStringBufferStringBuilder
String Pool serves as the storage area.Heap Memory serves as the storage area.Heap memory serves as the storage area.
Strings are ImmutableThey are mutableThey are mutable
Strings are generally not used in the case of a threaded environment.StringBuffer is suitable for multiple threadsStringBuilder is suitable for an environment with single threads
It is quite slow to work with a stringSpeed of a StringBuffer is more than String and less than StringBuilderStringBuilder is the fastest in performing operations.

Q3. Why is string made immutable in JAVA?

Immutable means unmodifiable or unchangeable.

Security is the major reason why strings in Java are made to be immutable. Strings in Java can be used to access data sources like files, databases, or even objects found across networks. Even sometimes, strings store passwords and usernames, which can’t be modified once created.

Q4. How to compare two strings in java?

We can compare two strings using the equals() method. Another method is to use the ‘==’ operator but try to avoid this method to compare two strings.

The reason behind this ‘equals()’ method compares the values of the two strings, whereas the ‘==’ operator compares the reference in the memory.

String S1 = "coding ninjas";
String S2 = new String("coding ninjas");
System.out.println(S1==S2); // returns false
System.out.println(S1.equals(S2)); // return true

Q5. How can you remove all the white spaces in a string?

Removal of white spaces in the String is termed as ‘Squeezing.’ Trimming from the left, right, and trimming the white spaces together combined in ‘Squeezing.’

public class WhiteSpaces
{
    static int ind;
   
    static void removal(String s)
    {
        for(ind = 0; ind < s.length(); ind++)
        {
            char ch = s.charAt(ind);
            if(ch != ' ')
            System.out.print(ch);
        }
    }
   
    public static void main (String args[])
    {
        SqueezeString.squeeze("   coding ninjas    ");
    }
}

The output of the program is:

codingninjas

Q6. What is a string constant pool?

The memory space allocated in the heap memory to store the string literals is called the string constant pool. 

No two string objects can have the same value in a string constant pool. 

Q7. How many objects are created in the following code snippet?

String s1 = "coding ninjas";
String s2 = new String ("coding ninjas");

Two objects are created in the above code snippet. 

  1. s1 String is created in the string constant pool as it is created by string literals.
  2. s2 String is created in heap memory as it is created by the ‘new’ operator. No new object will be created in the string constant pool as it is already created by s1.

Q8. How many objects are created in the following code snippet?

String s1 = new String ("coding ninjas");
String s2 = new String ("coding ninjas");

Three objects will be created.

  1. For string s1, two objects will be created, one in heap memory and the other in String constant pool.
  2. For string s2, only one object will be created in heap memory, but no new object will be created in the string constant pool as the object with the same value is already present in the string constant pool.

Q9. Difference between string in C and string in java.

C string is a null-terminated character array, whereas String in Java is an object. String objects in java allow us to call various methods like substring(), toLowerCase(), length().

Q10. What does the string intern() method do?

When the intern method is invoked, if the String constant pool already contains a string equal to the String object as determined by the equals(Object) method, the String from the pool is returned.

Otherwise, the String object is added to the pool, and a reference to the String object is returned.

The task of the intern() method is to put String (which is passed to the intern method) into the string constant pool.

Q11. How can you split the string in java?

split() method of java.lang.String is used to split a comma-separated String. We can also use StringTokenizer to split the comma-separated String, but the split() method is easier and better to use as it returns an array of strings that we can further manipulate in the code.

Q12. Write a program to remove a given character from a string.

We can use the replaceAll() method to replace all the string occurrences in the given String. But here, a character is given as an argument. So, first, we have to convert this character into a string; then, by using the replaceAll() method, we can remove all the occurrences of the given character in the required String.

private static String removeChar(String S, char ch)
{
    if (S == null)
    {
        return null;
    }

    return str.replaceAll(Character.toString(ch), "");
}

Q13. Why string is not used for storing the passwords rather a char array is preferred for the same?

String is immutable in Java and stored in the string constant pool. Once the string object is created, it is stored in the pool unless garbage is collected.

In the case of passwords, if String is used, it will be available in the memory for a longer duration. It will be a security risk as anyone with access to the memory dump can access the password.

On the other hand, if we use a char array for storing the passwords, we can set it to blank once we are done creating it. So we can control for how long the password will be available in the memory. That’s why a char array is preferred for storing the passwords rather than String.

Q14. Which object is popular as the HashMap key and why?

String is the popular HashMap key.  This is because String is immutable in Java. So, the hashcode of the String is cached every time it is created and doesn’t need to be calculated again. This makes the processing faster than other HashMap keys. 

Q15. How will you create an immutable class in java?

You can create an immutable class in Java by implementing the following points:

  1. First, make the class as final such that the class cannot be further inherited.
  2. Then, make all the data members private such that they will not be accessible from outside the class.
  3. Do not provide setter methods for the variables.
  4. Deep copy of objects should be performed in the getter methods.

Advanced Level String Interview Questions

Q16. Explain Character Encoding. What is the difference between UTF-8 and UTF-16?

Encoding is the way to convert the data from one form to another. Character encoding refers to the method when a character is represented in bytes.

UTF-8 uses 1 byte or 8 bits of memory to store the character, whereas UTF-16 uses 2 bytes or 16 bits of memory to store the character.

Q17. How does the substring() method fix memory leakage?

Substring shares the same character array as the String. If the original String is too large, it will lead to a memory leak, and sometimes it will not be retained.

Then, the original String will be retained by the substring as the size of the substring is smaller than the original String. It will further result in the prevention of large arrays being garbage collected. 

Q18. Write a program to check whether the two given strings are anagrams.

Two strings are said to be anagrams if the two strings contain the same set of characters, but the order can be different.

For example: “coding” and “dincog” are anagrams. “ninjas” and “jasnni” are anagrams.

There are two approaches to solve this problem:

Approach 1: This approach involves sorting both the strings lexicographically and then comparing both strings. This approach will cost O(N * log(N) + M * log(M)) time where ‘M’ and ‘N’ represent the length of two strings. 

Approach 2: This approach involves storing the frequencies of each character of the two strings and then comparing the occurrence of the characters in the two strings. This approach will cost O(N + M) time and O(26) space where ‘N’ and ‘M’ represent the length of the two strings.

For the code and algorithm, you can refer to the link – Anagrams.

Q19. Write a program to print all permutations of String in Java.

Let’s say a given string is “abc” so all possible permutations of this string will be “abc”, “acb”, “bac”, “bca”, “cab”, “cba”. So in this question, we have to generate all the permutations of the characters in the given String.

There are two approaches to solve this problem:

Approach 1: This approach follows backtracking. In this, a character is made to be fixed at a position, and permutations of the rest of the characters will be computed. This approach will cost O(N! * log(N!)) time and O(N * N!) space.

Approach 2: This approach is way more optimized than Approach 1. In this approach, the first permutation will be the String sorted in increasing order, and the last permutation will be the String sorted in decreasing order. This approach will cost O(N * N!) time and O(N * N!) space.

For the code and algorithm, you can refer to the link – String Permutations.

Q20. Write a program to swap two string variables without using a third variable in Java.

Suppose we have two strings, String a = “Coding” and String b = “Ninjas.” After swapping, the result should be a = “Ninjas” and b = “Coding.”

For this we first concatenate string b to string a, So a = “CodingNinjas”. Now we will store the substring starting from index 0 and of length = a.length() – b.length() in string b. Now b = “Coding”.

Now store the substring from index = b.length() till the end of the String a in String a. After this, String a = “Ninjas.”

You can refer to the below code snippet for the logic.

public class Solution { 
    public static void main(String args[]) { 
        String a = "Coding"; 
        String b = "Ninjas"; 
        System.out.println("Before swap: " + a + b);  
        a = a + b;  
        b = a.substring(0, a.length() - b.length());  
        a = a.substring(b.length());  
        System.out.println("After swap : " + a + b);  
    } 
}

The output for the code is:

Before swap: CodingNinjas
After swap: NinjasCoding

Q21. What is StringTokenizer in Java?

To break the String into tokens, Java.util.StringTokenizer is used. StringTokenizer doesn’t provide the facility to differentiate identifiers, quoted strings, and numbers like the StreamTokenizer class.

There are six useful methods of the StreamTokenizer class:

  1. String nextToken() – This will return the next token from the StringTokenizer cobject.
  2. Object nextElement() – This method is same as nextToken() but it will return an object.
  3. boolean hasMoreTokens() – This method checks if there are more tokens available or not.
  4. int countTokens() – This method returns the total number of tokens 
  5. String nextToken(String delim) – This method returns the next token based on the delimiter.
  6. Boolean hasMoreElements() – This method is same as hasMoreTokens().

Q22. Write a program in Java to reverse the order of words in a string without using the reverse() method.

In this question, you will be given a string of space-separated words like “hey there hope you are having a good time.” You have to reverse the order of words in the given String like “time good a having are you hope there hey.”

The approach is to use an array to store the words of the String. Now traverse the array in the reverse direction and append the words again in the given String.

This approach will cost O(N) time and O(N) space, where ‘N’ denotes the length of the given String.

You can refer to the link for the code and algorithm – Reverse the order of words in a string.

Q23. Suppose there is a code in which a lot of string modification and string concatenation is going on. Which class among StringBuffer, String, and StringBuilder, will improve the performance of the code, keeping thread-safety of the code in mind?

If we use the String class, because of its immutable nature, it will create a new object after every modification in the String, which will badly affect the performance of the code.

The StringBuilder class is not thread-safe because StringBuilder is not synchronized.

So, in this scenario, StringBuffer will give better performance.

Q24.Why is Java provided with String constant pool as we can store the objects in heap memory?

String constant pool provides the facility of reusability of the existing string objects. When a new string object is created using the string literals, then JVM first checks in the pool if this String already exists or not. If it exists, then it will reference the existing String rather than creating a new object. This will help in the speeding up of the application and also helps in saving the memory as no two objects will have the same content.

Q25. What is the similarity and difference between String and StringBuffer class?

The similarity between the two is that both are thread-safe. And the difference between the two is that String objects are immutable, and StringBuffer objects are mutable.

Q26.Write a code in Java to prove that String objects are immutable.

Generate two string objects using string literals, say s1 = “codingninjas” and s2 = “codingninjas.” As string objects generated with string literals are stored in the string constant pool, any two objects can’t have the same values. Therefore, both s1 and s2 will be pointing to the same object.

Then s1==s2 will return true.

Let’s just modify s1 by concatenating “article” as s1 = s1 + “article”. After this s2 = “codingninjasarticle”. This statement will concatenate “article” to the object which s1 is pointing to and reassigns reference of that object back to s1.

Now, s1==s2 will give false output as s1 and s2 are now pointing to different objects in the pool as when we modified s1, a new object is created in the pool, and its reference is assigned to s1.

For clarification, refer to the below code snippet.

public class CodingNinjas
{
    public static void main(String[] args)
    {
        String s1 = "codingninjas";

        String s2 = "codingninjas";

        System.out.println(s1 == s2);     //Output : true

        s1 = s1 + "article";

        System.out.println(s1 == s2);     //Output : false
    }
}

Q27. What will be the output of the following code?

public class Demo
{
    public static void main(String[] args)
    {
        System.out.println('c' + 'o' + 'd' + 'e');
    }
}

The output of the above code will be 411. The reason is the print statement has character literals in single quotes, so instead of concatenation, the corresponding ASCII value of each character is added, and the result is displayed as 411.

Q28. What is the difference between s1.equals(“book”) and “book” .equals(s1) where s1 represents the object of a string?

If the s1 value is “book”, then both statements will return true. The difference arises when s1 will be a null value. In that case, s1.equals(“book”) will throw the null pointer exception, and on the other hand “book” .equals(s1) will return false.

Q29. What will be the output of the following code?

public class StringTest
{
public static void main(String[] args)
    {
String s1 = new String("coding");
String s2 = new String("CODING");
System.out.println(s1 = s2);
}
}

The output of this code will be CODING because s2 will be assigned to s1. The confusion arises between ‘==’ and ‘=’ operators. That’s why this question is a simple yet tricky one.

Q30. What will be the output of the following code?

String s1 = "coding";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));

The output of this code will be false as s2 is not of type string. You can learn more about the StringBuffer class from here.

Key Takeaways

This article discussed the String Interview Questions of Java from the intermediate to advanced level. You can practice the same String Interview Questions for Python as well. Once you are done with this, you can check out our Interview Preparation Course to level up your programming journey and get placed at your dream company.

Till then, all the best for your future endeavors. Keep Coding!!

By: Deepanshu Dhingra