Java String Interview Questions And Answers

In this article, we will discuss some important Java String Interview Questions and Answers for beginners as well as experienced candidates.
Before we get started, check out Complete guide to Java String, StringBuilder, and StringBuffer methods
I would like to share my experience with Java String Interview questions. I have listed these most commonly asked interview questions and answers regarding String handling in Java.

YouTube Video

1. What is String in Java?

A String is a sequence of characters. In the Java programming language, strings are objects. A String is immutable so once a String object is created, its content can't be changed.
From Java API, the String is a Java Class defined in java.lang package. It’s not a primitive data type like int and long
Below is the String Class hierarchy diagram for quick reference - 

2. Is String a primitive type or an object in Java?

The String is an object in Java, not a primitive type.

3. What are the different ways to create String Objects?

There are two ways to create a String object:
  1. By string literal
  2. By new keyword

1. Using String Literal

We can create a String literal using double quotes in Java:
For Example:
String s="javaguides";

2. Using new Keyword

We can create a String object using a new keyword in Java:
    String str = new String("Java Guides");

4. What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can’t modify them once they are created. They are final in nature. Where mutable objects are concerned, you can perform modifications to them.

For example, String is immutable in Java, once you created a String object then you can't modify it. Any modification leads to a new String object being created.
String str = "Hello";
str.concat(" World");  // Returns a new string, the original 'str' is unchanged.
Whereas StringBuilder or StringBuffer is a mutable in Java so once you create an object of StringBuilder or StringBuffer class then you can modify it.
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World");  // Modifies the original object.

5. What is String Constant Pool?

String Constant Pool is a pool of string literals stored in the Java Heap memory. When a string literal is created, Java checks the String Constant Pool first. If the string already exists, it returns a reference to the pooled instance; otherwise, it creates a new String and places it in the pool. 

6. How String Constant Pool Works

When a string is created in Java, the JVM first checks the string constant pool. If a string with the same value already exists in the pool, a reference to that string is returned. Otherwise, a new string object is created in the pool, and a reference to this new object is returned. This process is called "interning."

For example:
String str1 = "JavaGuides";  // These two strings are both references
String str2 = "JavaGuides";  // to the same object in the constant pool
In the above example, the JVM will only create one object in the string constant pool. Both str1 and str2 will point to the same object in the pool.

Read more at String Constant Pool

7. Does String is thread-safe in Java?

Yes, Strings are immutable in Java so once we create a String object then we can't change its content. Hence it’s thread-safe and can be safely used in a multi-threaded environment. 

8. Difference between == and equals() method in Java

In Java, the == operator is used to compare the references of objects, i.e., it checks if two variables point to the same memory location. 

On the other hand, the equals() method is used to compare the content or values of objects, and it is usually overridden by classes to provide custom comparison logic.
public class Test { 
    public static void main(String[] args) 
    { 
        String s1 = new String("HELLO"); 
        String s2 = new String("HELLO"); 
        System.out.println(s1 == s2); 
        System.out.println(s1.equals(s2)); 
    } 
} 
Output:
false
true

9. Difference between String and StringBuilder?

  1. A String is immutable in Java, while a StringBuilder is mutable in Java
  2. A String is thread-safe, whereas StringBuilder is not a thread-safe
  3. The performance of the String is slower than StringBuilder in the case of multiple concatenation operations. This is because the string is immutable in Java, and the concatenation of two string objects involves creating a new object
  4. A String class overrides the equals() method of the Object class. So you can compare the contents of two strings by the equals() method. StringBuilder class doesn't override the equals() method of an Object class.

10. Difference between String and StringBuffer

  1. A String class is immutable and whereas the StringBuffer class is mutable.
  2. A String is slow and consumes more memory when you perform too many concatenation String operations because every time it creates a new instance. But StringBuffer is fast and consumes less memory when you cancat strings.
  3. A String class overrides the equals() method of an Object class. So you can compare the contents of two strings by the equals() method. StringBuffer class doesn't override the equals() method of an Object class.
  4. String class uses a String constant pool to store the objects whereas StringBuffer class uses heap memory to store its objects.

11. Difference between StringBuilder and StringBuffer?

  1. A StringBuilder is not a thread-safe, whereas StringBuffer is a thread-safe
  2. A StringBuffer is slower than StringBuilder. Because StringBuffer is a thread-safe implementation and therefore slower than the StringBuilder.

12. String vs StringBuilder vs StringBuffer in Java

Here is the summary of the differences between String, StringBuilder and StringBuffer in Java

13. What does the String intern() method do?

The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool.

Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.

We can call the intern() method to tell the JVM to add it to the string pool if it doesn't already exist there, and return a reference of that interned string:
        String s1 = "abc";
        String s2 = new String("abc");
        String s3 = new String("foo");
        String s4 = s1.intern();
        String s5 = s2.intern();

        System.out.println(s3 == s4);
        System.out.println(s1 == s5);
Output:
false 
true 

15. Why String is a popular HashMap key in Java?

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for keys in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

15. How many objects will be created in the following code and where they will be stored?

String s1 = new String("javaguides");
 
String s2 = "javaguides";

Answer:

Two objects will be created. Here's the breakdown: 
When the code encounters the string literal "javaguides", it ensures there's an instance of it in the String Pool. If not already present, one is created. This is our first object. 

Using the new keyword forces Java to create a new String object in the heap memory, regardless of whether the content is already present in the String Pool or not. This is our second object. 

For s2, no new object is created. Instead, the reference from the String Pool (from our first object) is simply assigned to s2

To summarize: 
  • 1 object is stored in the String Pool (part of the heap). 
  • 1 object is directly stored in the heap memory (outside the StringPool).

16. How many objects will be created in the following code and where they will be stored?

String s1 = new String("javaguides");
 
String s2 = new String("javaguides");

Answer:

Three objects will be created. Here's the breakdown: 

String Literal "javaguides": When the code encounters the string literal "javaguides", it ensures there's an instance of it in the String Pool. If not already present, one is created. This is our first object. 

new String("javaguides") for s1: Using the new keyword forces Java to create a new String object in the heap memory, regardless of whether the content is already present in the String Pool or not. This is our second object. 

new String("javaguides") for s2: Again, using the new keyword causes another separate String object to be created in the heap memory. This is our third object. 

To summarize: 
  • 1 object is stored in the StringPool (part of the heap). 
  • 2 objects are directly stored in the heap memory (outside the StringPool).

17. How do you concatenate two strings in Java?

In Java, you can concatenate two strings using either the + operator or the concat() method of the String class. 

Example: Using the + operator:
String result = "Hello" + " World";
Using the concat() method:
String result = "Hello".concat(" World");
Both approaches will produce the string "Hello World".

18. What are the methods to compare two strings in Java?

In Java, you can compare two strings using the following methods: 
equals(): Compares the content of two strings. Returns true if they have the same content, false otherwise. 

equalsIgnoreCase(): Compares the content of two strings, ignoring case differences. 

compareTo(): Lexicographically compares two strings. Returns 0 if they are the same, a negative integer if the first string comes before the second, or a positive integer if the first string comes after the second. 

For example:
String str1 = "Hello";
String str2 = "hello";

boolean isEqual = str1.equals(str2);           // false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true
int comparisonResult = str1.compareTo(str2);   // -32 (because 'H' is 32 units away from 'h')

19. Java String Programs Asked in the Interviews

All these Java String programs have step-by-step explanations along with their output.

Comments