Java String Interview Questions And Answers


In this article we will discuss some important Java String Interview Questions and Answers.
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.
  1. What is String in Java?
  2. What are different ways to create String Object?
  3. Write a method to check if input String is Palindrome?
  4. What is String Constant Pool?
  5. Does String is thread-safe in Java?
  6. Difference between == and .equals() method in Java
  7. Difference between String, StringBuffer and StringBuilder?
  8. Why String is Immutable or Final in Java ?
  9. What do you mean by mutable and immutable objects?
  10. Difference between String and StringBuffer
  11. Which one will you prefer among “==” and equals() method to compare two string objects?
  12. What does String intern() method do?
  13. Why String is popular HashMap key in Java?
  14. What is the similarity and difference between StringBuffer and StringBuilder class?
  15. Write a Java program to Count Number of Duplicate Words in String
  16. Write a Java Program to Count Number of Words in Given String
  17. Write a Java Program to Count the Number of Occurrences of Substring in a String
  18. Write a Java Program to Count the Occurrences of Each Character in String
  19. Write a Java Program to Check if Input String is Palindrome
  20. Write a Java Program to Find all Permutations of String
  21. Write a Java Program to Merge two String Arrays
  22. Write a Java Program to Remove Duplicate Words from String
  23. Write a Java Program to Reverse a String(5 ways)
  24. Write a Java Program to Reverse Each Word of a String
  25. Write a Java Program to Swap Two Strings
  26. How to Check if the String Contains only Digits?
  27. How to Check if the String Contains only Letters?
  28. How to Check If the String Contains Only Letters or Digits? 
The PDF of this article is available at Free Java eBooks, Guides, PDF Resources.

1. What is String in Java?

String is a Java Class defined in java.lang package. It’s not a primitive data type like int and long. Strings are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. String in immutable and final in Java and JVM uses String Constant Pool to store all the String objects.
Below is the String Class hierarchy diagram for quick reference - 

2. What are different ways to create String Object?

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

Using String Literal

Java String literal is created by using double quotes. 
For Example:
String s="javaguides";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If a string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="javaguides";
String s2="javaguides";
 //will not create new instance
To know more detail how the String Pool works on Guide to Java String Constant Pool.
Now the question is why java uses a concept of a string literal? It's simple, to make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

Using new Keyword

Let's create a simple example to demonstrate by creating String objects using the new keyword.
public static void main(String[] args) {
    String str = new String("Java Guides");
     // create String object using new Keyword
    int length = str.length();
    System.out.println(" length of the string '" + str + "' is :: " + length);
}
Output:
 length of the string 'Java Guides' is:: 11 
From the above example, JVM will create a new string object in normal(non-pool) heap memory and the literal "Java Guides" will be placed in the string constant pool. The variable str will refer to the object in heap(non-pool). To create a String initialized by an array of characters, Here is an example:
char chars[] = {
    'a',
    'b',
    'c'
}

;
String s = new String(chars);

3. Write a method to check if the input String is Palindrome?

We will discuss three approaches to check if the input String is Palindrome. We will write methods, not a complete program. Check out http://www.javaguides.net/2018/08/java-program-to-check-if-input-string-is-palindrome.html article for complete program and output
  1. Reversing a String
public static boolean checkPalindrome(String input) {

    // Check error conditions
    if (isEmpty(input)) {
        return false;
    }
    String reverse = "";
    int length = input.length();

    for (int i = length - 1; i >= 0; i--) {
        reverse = reverse + input.charAt(i);
    }

    if (input.equals(reverse)) {
        System.out.println(input + " is palindrome = " + true);
    } else {
        System.out.println(input + " is palindrome = " + false);
    }
    return false;
}
  1. Simple for loop logic
private static void checkPalindromeString(String input) {
    boolean result = true;
    int length = input.length();
    for (int i = 0; i < length / 2; i++) {
        if (input.charAt(i) != input.charAt(length - i - 1)) {
            result = false;
            break;
        }
    }
    System.out.println(input + " is palindrome = " + result);
}
  1. Reversing a String using StringBuilder reverse() Method
private static boolean isPalindrome(String str) {
    if (str == null)
        return false;
    StringBuilder strBuilder = new StringBuilder(str);
    strBuilder.reverse();
    return strBuilder.toString().equals(str);
}

4. What is String Constant Pool?

String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.

5. Does String is thread-safe in Java?

Strings are immutable, so we can’t change its value in the program. Hence it’s thread-safe and can be safely used in the multi-threaded environment.

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

In general, both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:
  1. Main difference between .equals() method and == operator is that one is a method and other is an operator.
  2. We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
  3. If a class does not override the equals method, then by default it uses equals(Object o) method of the closest parent class that has overridden this method. See this for detail
  4. Coding Example: // Java program to understand
    // the concept of == operator
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

7. Difference between String, StringBuffer and StringBuilder?

  1. String is immutable whereas StringBuffer and StringBuilder are mutable classes.
  2. StringBuffer is a thread safe and synchronized whereas StringBuilder is not, that's why StringBuilder is faster than StringBuffer.
  3. String Concat  + operator internally uses StringBuffer or StringBuilder class.
  4. For String manipulations in a non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

8. Why String is Immutable or Final in Java?

String is immutable in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information cannot be modified. There are several benefits of String because it’s immutable and final.
  1. String Pool is possible because String is immutable in java.
  2. It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password etc.
  3. Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.
  4. Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

9. 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 as mutable objects are concerned, you can perform modifications to them.

10. Difference between String and StringBuffer

  1. String class is immutable and whereas StringBuffer class is mutable.
  2. String is slow and consumes more memory when you concat too many strings because every time it creates new instance. But StringBuffer is fast and consumes less memory when you cancat strings.
  3. String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class.

11. Which one will you prefer among “==” and equals() method to compare two string objects?

Say, equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations. So, rather stick to equals() method to compare two string objects.

12. What does String intern() method do?

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. This method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings. For example-
public class InternExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String newStr = new String("javaguides");
        System.out.println(newStr.intern().equals(str));
        System.out.println(newStr.equals(str));
        newStr.intern();
        str.intern();
    }
}
Output:
true true 

13. Why String is 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 key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

14. What is the similarity and difference between StringBuffer and StringBuilder class?

The main similarity between StringBuffer and StringBuilder class is that both produces mutable string objects. The main difference between them is that StringBuffer class is thread safe where as StringBuilder class is not thread safe.

15. Write a Java program to Count Number of Duplicate Words in String

16. Write a Java Program to Count Number of Words in Given String

17. Write a Java Program to Count the Number of Occurrences of Substring in a String

18. Write a Java Program to Count the Occurrences of Each Character in String

19. Write a Java Program to Check if Input String is Palindrome

20. Write a Java Program to Find all Permutations of String

21. Write a Java Program to Merge two String Arrays

22. Write a Java Program to Remove Duplicate Words from String

23. Write a Java Program to Reverse a String(5 ways)

24. Write a Java Program to Reverse Each Word of a String

25. Write a Java Program to Swap Two Strings

26. How to Check if the String Contains only Digits?

27. How to Check if the String Contains only Letters?

28. How to Check If the String Contains Only Letters or Digits?

29. How to convert String to Char and Vice Versa?

We can use the charAt method to get the character at a given index or we can use toCharArray() method to convert String to a character array.
Here is a simple example to convert String to a character array.
public class StringToCharJava {

    public static void main(String[] args) {
        String str = "journaldev";

        //string to char array
        char[] chars = str.toCharArray();
        System.out.println(chars.length);

        //char at specific index
        char c = str.charAt(2);
        System.out.println(c);

        //Copy string characters to char array
        char[] chars1 = new char[7];
        str.getChars(0, 7, chars1, 0);
        System.out.println(chars1);
    }
}

30. Can we use String in Switch Case?

This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier Java versions don’t support this.
Beginning with JDK 7, we can use a string to control a switch statement. Below example demonstrates use a string to control a switch statement.
package net.javaguides.corejava.controlstatements.switchcluase;

public class StringsSwitch {
    public static void main(String args[]) {
        String str = "two";
        switch (str) {
            case "one":
                System.out.println("one");
                break;
            case "two":
                System.out.println("two");
                break;
            case "three":
                System.out.println("three");
                break;
            default:
                System.out.println("no match");
                break;
        }
    }
}
Output:
two

I kindly suggest that if you have other interview questions regarding Java String Handling that will help others prepare for their interview, leave a note in the comments below!

References

Java Lang Package Tutorial
Java String API Guide
Java String Interview Questions and Answers

Comments