Tutorial

Java String Interview Questions and Answers

Updated on November 23, 2022
authorauthor

Pankaj and Andrea Anderson

Java String Interview Questions and Answers

Introduction

String is one of the most widely used Java classes. This article provides some practice questions and answers about String to help you prepare for an interview.

You can also try the Java String Quiz to test your knowledge of the String class.

What is the String class in Java? Is String a data type?

String is a class in Java and is defined in the java.lang package. It’s not a primitive data type like int and long. The String class represents character strings. String is used in almost all Java applications. String in immutable and final in Java and the JVM uses a string pool to store all the String objects. You can instantiate a String object using double quotes and you can overload the + operator for concatenation.

What are some different ways to create a String object in Java?

You can create a String object using the new operator or you can use double quotes to create a String object. For example:

String str = new String("abc");
String str1 = "abc";

There are several constructors available in the String class to get a String from char array, byte array, StringBuffer, and StringBuilder.

When you create a String using double quotes, the JVM looks in the String pool to find if any other String is stored with the same value. If the String is already stored in the pool, the JVM returns the reference to that String object. If the new String is not in the pool, the JVM creates a new String object with the given value and stores it in the string pool. When you use the new operator, the JVM creates the String object but doesn’t store it in the string pool. You can use the intern() method to store the String object in String pool or return the reference if there is already a String with equal value present in the pool.

Write a Java method to check if an input string is a palindrome.

A string is a palindrome if its value is the same when reversed. For example, aba is a palindrome string. The String class doesn’t provide any method to reverse the string but the StringBuffer and StringBuilder classes have a reverse() method that you can use to check whether a string is a palindrome. For example:

private static boolean isPalindrome(String str) {
    if (str == null)
        return false;
    StringBuilder strBuilder = new StringBuilder(str);
    strBuilder.reverse();
    return strBuilder.toString().equals(str);
}

Sometimes, an interviewer might request that you don’t use any other class to check for a palindrome. In that case, you can compare characters in the string from both ends to find out if it’s a palindrome. For example:

private static boolean isPalindromeString(String str) {
    if (str == null)
        return false;
    int length = str.length();
    System.out.println(length / 2);
    for (int i = 0; i < length / 2; i++) {
         if (str.charAt(i) != str.charAt(length - i - 1))
            return false;
    }
    return true;
}

Write a Java method that will remove a given character from a string object.

We can use the replaceAll method to replace all of the occurrences of a string with another string. The important point to note is that replaceAll() accepts String as argument, so you can use the Character class to create a string and use it to replace all the characters with an empty string.

private static String removeChar(String str, char c) {
    if (str == null)
        return null;
    return str.replaceAll(Character.toString(c), "");
}

How can you make a String upper case or lower case in Java?

You can use the String class toUpperCase and toLowerCase methods to get the String object in all upper case or lower case. These methods have a variant that accepts a Locale argument and use the rules of the given locale to convert the string to upper or lower case.

What is the String subSequence method?

Java 1.4 introduced the CharSequence interface and the String class implements this interface, which is why the String class has the subSequence method. Internally, the subSequence method invokes the String substring method.

How do you compare two strings in a Java program?

Java String implements the Comparable interface, which has two variants of the compareTo() method. The compareTo(String anotherString) method compares the String object with the String argument passed lexicographically. If the String object precedes the argument passed, it returns a negative integer, and if the String object follows the argument passed, it returns a positive integer. It returns zero when both the String objects have the same value. In this case, the equals(String str) method also returns true. The compareToIgnoreCase(String str) method is similar to the first one, except that it ignores the case. It uses Comparator with CASE_INSENSITIVE_ORDER for case insensitive comparison. If the value is zero, then equalsIgnoreCase(String str) will also return true.

How do you convert a String to a character array in Java?

A String object is a sequence of characters, so you can’t convert it to a single character. You can use use the charAt method to get the character at given index or you can use the toCharArray() method to convert a string to character array. Learn more about converting a string to a character array.

How do you convert a String to a byte array in Java?

You can use the getBytes() method to convert a String object to a byte array and you can use the constructor new String(byte[] arr) to convert a byte array to String object. Learn more about converting a string to a byte array.

Can you use String in switch case in Java?

Java 7 extended the capability of switch case to Strings; earlier Java versions don’t support this. If you’re implementing conditional flow for strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions. Learn more about Java switch case string.

Write a Java program to print all permutations of a string.

You’ll need to use recursion to find all the permutations of a string. For example, the permutations of AAB are AAB, ABA and BAA. You also need to use Set to make sure there are no duplicate values. Learn more about finding all the permutations of a string.

Write a Java function to find the longest palindrome in a given string.

A string can contain palindrome substrings within it. Learn more about how to find the longest palindrome substring in a string.

What are the differences between String, StringBuffer, and StringBuilder in Java?

A String object is immutable and final in Java, so whenever you manipulate a String object, it creates a new String object. String manipulations are resource consuming, so Java provides two utility classes for string manipulations, StringBuffer and StringBuilder.

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized, while StringBuilder operations are not thread-safe. You should use StringBuffer in a multi-threaded environment and use StringBuilderin a single-threaded environment. StringBuilder performance is faster than StringBuffer because of no overhead of synchronization.

Learn more about the differences between String, StringBuffer and StringBuilder and benchmarking of StringBuffer and StringBuilder.

Why is String immutable in Java?

String is immutable in Java because this offers several benefits:

  • String pool is possible because String is immutable in Java.
  • It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as a database username or password.
  • Since String is immutable, it’s safe to use in multi-threading and you don’t need any synchronization.
  • Strings are used in Java class loaders and immutability provides assurance that the correct class is getting loaded by the ClassLoader class.

Learn more about why String is immutable in Java.

How do you split a string in Java?

You can use split(String regex) to split the String into a String array based on the provided regular expression.

Why is a character array preferred over String for storing passwords in Java?

A String object is immutable in Java and is stored in the string pool. Once it’s created it stays in the pool until garbage collection completes, so even though you’re done with the password it’s available in memory for longer duration. It’s a security risk because anyone having access to memory dump can find the password as clear text. If you use a character array to store password, you can set it to blank once you’re done with it. You can control for how long it’s available in memory and that avoids the security threat.

How do you check if two Strings are equal in Java?

There are two ways to check if two Strings are equal. You can use the == operator or the equals() method. When you use the == operator, it checks for the value of String as well as the object reference. Often in Java programming you want to check only for the equality of the String value. In this case, you should use the equals() method to check if two Strings are equal. There is another function called equalsIgnoreCase that you can use to ignore case.

String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");

System.out.println("s1 == s2 ? " + (s1 == s2)); //true
System.out.println("s1 == s3 ? " + (s1 == s3)); //false
System.out.println("s1 equals s3 ? " + (s1.equals(s3))); //true

What is the string pool in Java?

The string pool is a pool of String objects stored in Java heap memory. String is a special class in Java and you can create a String object using the new operator as well as by providing values in double quotes. Learn more about the Java string pool.

What does the Java 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 returns a String object that has the same contents as this String but is guaranteed to be from a pool of unique strings.

Is String thread-safe in Java?

A String object is immutable, so you can’t change its value after creation. This makes the String object thread-safe and so it can be safely used in a multi-threaded environment. Learn more about thread Safety in Java.

Since a String object 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 the key in a Map since its processing is faster than other HashMap key objects.

Guess the Output

Test yourself by guessing the output of the following Java code snippets.

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

The output is DIGITALOCEAN because the code assigns the value of String s2 to String s1. = is an assignment operator that assigns the value of y to x in the format (x = y). == is a comparison operator that would check if the reference object is the same for the two strings.


public class Test {
    
   	 public void foo(String s) {
   	 System.out.println("String");
   	 }
    
   	 public void foo(StringBuffer sb) {
   	 System.out.println("StringBuffer");
   	 }
    
   	 public static void main(String[] args) {
   		new Test().foo(null);
   	}
    
}
Output
Test.java:12: error: reference to foo is ambiguous
   		new Test().foo(null);
   		           ^
  both method foo(String) in Test and method foo(StringBuffer) in Test match

This code results in a compile time error because both foo methods have the same name and the call for the foo method in main is passing null. The compiler doesn’t know which method to call. You can also refer to the method X is ambiguous for the type Y error.


String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2);
Output
false

The output is false because the code uses the new operator to create the String object, so it’s created in the heap memory and s1 and s2 will have a different reference. If you create the strings using only double quotes, then they will be in the string pool and it will print true.


String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));
Output
false

The output is false because s2 is not of type String. The equals() method implementation in the String class has an instanceof operator to check if the type of passed object is String and return false if the object is not String.


String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 == s2);
Output
false

The output is false. The intern() method returns the String object reference from the string pool. However, the code doesn’t assign it back to s2 and there is no change in s2 and sos1 and s2 have a different object reference. If you change the code in line 3 to s2 = s2.intern();, then the output will be true.

How many String objects are created by the following code?

String s1 = new String("Hello");  
String s2 = new String("Hello");
Answer

The answer is three. The code in line 1 creates a String object with the value Hello in the string pool (first object) and then creates a new String object with the value Hello in the heap memory (second object). The code in line 2 creates a new String object with value Hello in the heap memory (third object) and reuses the Hello string from the string pool.

Conclusion

In this article you reviewed some Java interview questions specifically about String.

Recommended Reading:

Java Programming Questions String Programs in Java

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Technical Editor


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 4, 2021

Thnxs, PankaJ! Very useful! 👍

- Manu

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 29, 2020

    Hello I am not able to find compareToIgnoreCase() method in Comparable interface

    - Devender Sharma

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 29, 2020

      How many objects will be created for both line and why? String str1 = “one”.concat(“two”).concat(“three”); //line #1 String str1 = str1 + “ABC”+“XYZ” //line #2

      - Keshav

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 23, 2020

        Hi Panakj, Good Collection on String. I have a question as below. When we create a String object with any method or you can say approach. Than we mention that JVM will check that the particular String is already exists in String Pool or not. My question is that how JVM will compare this string with string pool data. Which function use by JVM for the comparison.

        - Keshav Jain

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 3, 2020

          Hi Pankaj, First of all, really great work posting these interview Q&A for the core concepts.  I think a correction is needed in Q# 2, as you said when we use new operator, it doesn’t get stored in pool but that’s contradicting your last practical example where you said there would be three strings. And i think the latter is correct. And it does store in pool in case its not there already. Please correct me if am wrong.

          - Sahil Dhuria

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 31, 2019

            Hi Sir, Thanks for advance. My question is to you what is the need of intern() method.As of now my understanding while creating instance to String using new operator it will be in String pool and heap memory as of your 6 question answer And when we create instance for string using double quote automatically store into string constant pool. Could you please clarify on the same

            - Ram

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 19, 2019

              This is some great work! Thanks for sharing.

              - prem kiran

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 12, 2019

                StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously but in diffrence you mentioned opposite StringBuilder is used for multi threaded application not StringBuffer

                - Tushar Desarda

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  October 24, 2018

                  Hi Pankaj, Good collection on Strings. Appreciate your efforts. I have only one doubt on String pool. Your statements regarding the below question is contradictory. What are different ways to create String Object? String str = new String(“abc”); String str1 = “abc”; When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool. When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool. you said that when we use new operator JVM creates string object but not stored in String pool. Need to use intern() to store in stringpool. for question 6 you are saying that using new operator it will also create in string pool. 6) How many String objects got created in below code snippet? String s1 = new String(“Hello”); String s2 = new String(“Hello”); Answer is 3. First – line 1, “Hello” object in the string pool. Second – line 1, new String with value “Hello” in the heap memory. Third – line 2, new String with value “Hello” in the heap memory. Here “Hello” string from string pool is reused. First – line 1, “Hello” object in the string pool. (we are not using intern() here then how it is stored in stringpool. Which one is true? Please do explain. Thanks in advance.

                  - Srividya

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 8, 2018

                    Method removeChar will not work if c is special reg exp character (e.g. ‘.’, ‘[’). String.replaceAll takes regexp as first parameter. You need to use String.replace instead of String.replaceAll.

                    - Leonid Talalaev

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more