Java String Interview Questions

String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept.  So, we should not ignore this section as it is important. In this section, we are going to enlist some important asked in Java String interview questions.

1) What are the differences between C, C++ strings and Java strings?

In C or C++, strings are not treated as objects. The C or C++ strings are terminated with the null character. However, Java strings are never terminated with the null character. Strings in Java are also treated as objects.

2) How are the strings stored in the memory?

The strings are stored in heap memory. The exact region where the strings are stored depends on their creation. If the strings are created using the new keyword, the strings are stored outside the string pool. If the strings are created using the string literals, the strings are stored inside the string pool.

3) Which one should be preferred, == operator or the equals() method to make a comparison between two string objects?

The equals() method should be preferred over the == operator, as the == operator only compares the references of the string objects, whereas the equals() method compares the content of the string objects.

4) What is the need for StringBuffer and StringBuilder classes when we have already got the String class?

In Java, the String class is always immutable. Therefore, any kind of modification in the objects of the String class leads to the creation of new objects, which lead to performance issue, as the creation of new objects consumes memory as well as time. To avoid the performance issue, the StringBuffer and StringBuilder classes were introduced in Java. Note that StringBuffer and StringBuilder classes create mutable objects.

5) Where the String pool is located in the memory?

The String pool is a portion of memory that is located inside the heap memory. It is used to store string literals.

6) How the substring() method works internally in Java?

The working of the substring() method varies if one moves from the JDK – 6 to JDK – 7. There was a major issue with the substring() method of the JDK – 6 version. It was found that there was a memory leak issue with the substring() method when dealt with the strings of the larger size. As Java strings are an array of characters, the substring() method for JDK – 6, shared the same characters of that string upon which the method is invoked. Consider the following code snippet.

Here, for the variable subStr, no new string is created, and the characters ‘H’, ‘e’, ‘l’, ‘l’ are shared between str and subStr. Thus, one can say both subStr and Str are holding the reference of the string “Hello India”. Now consider the following scenario.

After doing str = null, the string object for “Hello India” is not eligible for the garbage collection as subStr is also holding the reference. This leads to a memory leak if the string is of a larger size. For example, if a string is comprising of thousand characters and the substring is sharing only three characters, then the string object of the thousand characters cannot be deleted, as its three characters are shared. Thus, only for 3 characters, it is not correct to hold the memory of 1000 – 3 = 997 characters.

To resolve this issue, the working of the substring() method was modified in the JDK – 7.  In JDK – 7, the substring() method does not share the characters. Instead of sharing the characters, a new string is created.

7) Predict the output of the following program with the explanation.


Explanation: At first glance, it seems that the value of j should be 7. However, the value is 9. The reason for the value 9 is the Java compiler. The compiler first parses the Unicode present in the code. Therefore, before any lexical translation \u000d is evaluated. The Unicode moves the following code in the next line. Thus, // \u000d j = 9; gets converted into the following.

Now, when the lexical translation happens, the value of j gets updated to 9.          

8) How many ways are there to create String objects?

There are three ways to create String objects.

1) By using a string literal.

2) By passing string in the constructor of the String class.

3)  Using character array

9) Is it valid to use string literals in the Switch case?

It depends on the JDK version. From JDK 7, it is valid to use string literals in the Switch case. Before JDK 7, it was not possible to use a string literal in the Switch case.

10) Name the character encoding used in Java 9.

In Java 9, the UTF-8 character encoding is used by default. When JVM starts, System.getProperty(“file.encoding”, “UTF – 8”); gets called. UTF-8 is used as default when the file.encoding attribute is absent. However, this encoding can be changed by the programmer.

11) Why a Java programmer gives priority to the char[] instead of a string while storing a password?

The password of any user is a piece of very sensitive information. Therefore, security is the main concern while storing the password. As String is immutable in Java, therefore when string is used for storing the password, the password remains in the String pool for a long time for serving the purpose of reusability. Thus, there are high chances that it will remain in the memory for a longer period of time, which may lead to a security threat. Also, one cannot change the content of string as it will lead to the creation of a new string.

Using the char[] array, one can explicitly wipe the password content after the validation is complete. In other words, one can manipulate the char[] array data, but not the data present in a string, as strings are immutable in Java.

12) What is StringJoiner in Java?

The java.util package provides the StringJoiner class that is used to generate a sequence of characters or strings. The generated strings are separated by a delimiter. The StringJoiner class also provides the facility to add prefix and suffix to the string. Whatever we can achieve using the StringJoiner class can be achieved using the StringBuilder class using the append() method. However, the StringJoiner class makes the code less verbose. The StringJoiner class is introduced in Java 8 and is a final class.

13) Explain the concept of String intern.

The intern() method ensures that only one copy of a string value is present in the string pool. Therefore, the intern() method puts the string in the string pool. By default, the string literals are created in the string pool as they use the intern() method implicitly. However, to put strings created using the new keyword in the string pool, we have to use the intern() method explicitly.

The intern() method returns the canonical representation of the string. When the intern() method is executed, a check is performed whether the string object is already present in the string pool or not. If it is present, its reference is returned; otherwise, a new string object is generated in the string pool.

14) Why key in a Java HashMap is usually a string?

String is usually used as a key in a Java HashMap because strings are immutable in Java. Thus, when the key of a Java HashMap is hashed, its value never changes in the case of a string, as the manipulation of string leads to the generation of a new string. Therefore, the hashed value can be cached to make the performance of the program better.

15) Explain the string subSequence() method.

The CharSequence interface declares the subSequence() method. As the String class implements the CharSequence interface, it has to define the subSequence() method. The subSequence() method internally calls the subString() method and returns a CharSequence.

16) Why is String final or immutable in Java?

Following are some of the reasons for the String to be final or immutable in Java:

  • String literals are always stored in the String pool. Therefore, the String class has to be immutable. Without immutability, the String pool cannot exist.
  • The Java classloader uses strings to load classes. The immutability of the strings ensures that the correct class is loaded.
  • String immutability provides safety when it is used in the multithreading environment. We do not need to worry about synchronization because of the immutability.

17) Is autoboxing or unboxing possible in Java strings? Why?

No, autoboxing or unboxing is not possible in strings. Autoboxing and unboxing are the features of the wrapper classes. Java recognizes Boolean, Byte, Character, Float, Integer, Long, Short, and Double classes as the wrapper class. Therefore, neither autoboxing nor unboxing is possible in Java strings.

18) String objects are unique from the other objects of the derived types in Java. Why?

The creation of objects in the other derived classes is only possible using the new keyword (barring the wrapper classes). However, the String objects can be created without using the new keyword. One more unique feature about the String objects is that one can concatenate two String objects using the + operator. Such relaxation is not provided to the other derived class.

19) Explain the format() method of the Java String class. How is it different from the printf() method?

The format() method of the Java String class is used to format the string. The printf() method also formats the string. The main difference between the printf() method and the format() method is that the printf() method prints the formatted string, and the format() method returns the formatted string.

20) Observe the following statements and decide which one is better.

In the above two statements, the second statement should be preferred over the first statement. We know that Strings are considered as objects in Java. Therefore, if the st1 is not initialized with any value, then the st1 contains the null value. Thus, the st1.equals(“Tutorial & Example”); gets translated to null.equals(“Tutorial & Example”); which results in the generation of NullPointerException.

The second statement does not face any issue. In case st1 becomes null, “Tutorial & Example”.equals(st1); gets converted into “Tutorial & Example”.equals(null); which does not give an exception and results in the false value. Thus, unlike the first statement, the second statement is not prone to any error or exception.

21) Consider a scenario in which we want to perform multiple string concatenation and modification. In such a case, which class should we use that improves the performance of the code and the code must be thread-safe?

We have three prominent classes in the field of strings. The String class, StringBuilder class, and the StringBuffer class.

The String class cannot be used as it is immutable. Thus, string concatenation or modification leads to the generation of new strings, which hampers the performance of the program. Hence, the String class cannot be used.

The StringBuffer class is mutable. Hence, one can perform the string concatenation of modification easily, without the creation of any new objects. Thus, the performance is improved. However, the StringBuffer class does not facilitate thread safety. Hence, the StringBuffer class also cannot be used in the given scenario.

The StringBuilder class is mutable. Hence, any manipulation operation does not generate a new object. Thus, this class also improves performance. The StringBuilder class provides the thread-safe facility. Therefore, the StringBuilder class is the most appropriate class that should be used in this scenario.

22) Explain how many objects are created when the below-mentioned two statements are executed simultaneously?

It seems that only two objects are created: one for first statement, and another for second statement. However, the total number of objects created is three: two for first statement, and one for second statement. First, the object for the string literal “Tutorial & Example” is created in the string pool, then another object is created outside the string pool in the heap memory, as we have used a new keyword.

For the second statement, a string literal is used. Therefore, JVM (Java Virtual Machine) checks whether the literal is present in the string pool or not. It is found that the string literal is not present in the pool. It is because Java is a case-sensitive language, and example and Example words are treated differently. Hence, an object is created for the second statement also.

23) What is the fastest way to copy a String array?

The arraycopy( ) method can be used to copy quickly an array of any type from one place to another. It is much faster than the equivalent loop written out longhand in Java. Here is an example of two arrays being copied by the arraycopy( ) method. First, a is copied to b. Next, all of a’s elements are shifted down by one. Then, b is shifted up by one.

static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };

static byte b[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 };

24) Is there any difference between == operator and equals() method?

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.

25) Are Strings thread-safe?

In Java, every immutable object is thread-safe. Hence, String is also thread-safe. Java provides the StringBuffer class that is thread-safe while the StringBuilder class is not thread-safe because it is mutable and does not use the synchronized keyword.

26) How to count the number of vowels present in a string using recursion?



27) How to count the number of words present in a string?



28) Write a program in Java to find the percentage of lowercase, uppercase, digits, and other characters from the given string.



29) Write a program in Java to find the permutation of the given string.

Permutation of the string can be achieved by the technique of backtracking. The following program shows the same.



30) Write a program in Java to find the minimum number of characters that must be added at the beginning of the given string to make it a palindrome.

It is one of the tricky questions that is frequently asked in interviews. The approach is to find the largest palindromic substring by removing the characters, one by one, from the end. The number of characters deleted is our answer. Let’s observe the following program for a better understanding.



The number of characters to be inserted to make the string palindrome are: 6

Pin It on Pinterest

Share This