Tutorial

Java String Interview Questions and Answers

Updated on November 23, 2022
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 author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 1, 2013

Can you please explain the statement "Strings are immutable, so we can’t change it’s value in program. " by a sample program

- Ayan

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 3, 2013

String str = "abc"; str = "xyz"; // here the value of Object str is not changed, a new String literal "xyz" is created and str is now holding reference to this new String. I would suggest you to go through this post to know the properties of a immutable class and how you can write your own immutable class. Immutable Classes in Java

- Pankaj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 13, 2013

String s1=new String(“Hello”) above code How many objects will create?

- siddu

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 15, 2013

There will be two objects created one is in heap and one is in constant pool. Ques… how and Why … How Everything that is inserted within the " " (double quote) is a string and JVM forces to allocate the memory in the Constantpool… ok fine. And we also know the new Keyword that is used to allocate the memory in the Heap. And as the SCJP standard in case of string making the object with new keyword is certainly memory lose. example: String s=new String(“Deepak”);//line 1 String s1=“Deepak”; the reference Id of “Deepak” object will be assigned to s1.because It is already in the pool.//see line1 Question Arise: What kind of Memory is used by the ConstantPool…Heap or other…

- Deepak Chauhan

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 14, 2014

String s=new String(“Deepak”); when u have create a String object by using new keword than every time create new object in heap; but by using literal String than check in the memory but here there are two object is created one is heap , and second in pool; public class java { public static void main(String arr[]) { String s=new String(“Deepak”); String s1=“Deepak”; String s2=new String(“Deepak”); System.out.println(s==s2); System.out.println(s==s1); } } output is false false that is solution

- Paramjeet Singh

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 19, 2021

    Hi, Thank you for providing the insight on this topic! My question here is what will happen to String “abc” stored in pool memory, meaning how long will exist and when & how the same will be removed from memory? Similarly what happens to object stored outside of constant pool memory?

    - Arun

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 16, 2013

      Hi Pankaj, There is always something new to learn in your posts. But I would like to correct one thing in above post. When we create a String using new keyword, a whole new reference is being assigned, not from a literal. Up to this its right. But this instance is not added into the String Pool until we call intern(). We can check it out by below example: String s1 = new String("abc"); // new object - not from pool. String s2 = "abc"; // tries to search it from pool. System.out.println(s1 == s2); // returns false that means s1 has not been added to pool.

      - Ravi

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 7, 2013

      Thanks Ravi, yes you are right. Corrected the post.

      - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 10, 2013

      Pankaj, I think you were right before. when we create string with String s1 = new String(“abc”) then two objects are created. One is created on heap and second on constant pool(created only if it is not there in the pool). Since we are using new operator to create string so s1 always refers to the object created on the heap. When we create string with String s2 = “abc” then s2 will refer to object created in the constant pool. No object will be created on the heap. Since s1 and s2 are referring to different objects s1 == s2 will return false. If we want s1 to refer object created on the pool then use s1.intern().

      - Amit Malik

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 10, 2013

      Thats what is mentioned here…

      - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 1, 2016

      please explain why intern() is needed if the object will be created in both constant pool and heap when we use new operator.

      - deepak

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 1, 2016

        Hi I’ve a query!! please correct me if I’m wrong. String s = new String(“Hello”); When above code is executed two objects will be created. One in heap another in SCP(String Constant Pool) So what is the need to use intern() explicitly.? Or when do we use intern() exactly?? by above discussion i got that object will not be added to SCP but its created.!! then where it is created.?

        - deepak

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 14, 2019

        I have the exactly same question

        - Rhicha

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 3, 2013

          Nice Material… Keep it up to make us knowledgeable…

          - Prosenjit

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 1, 2013

            Thanks for finally talking about > Java String Interview Questions and Answers | JournalDev < Loved it!

            - aicotutorial.com

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 24, 2013

              Hi pankaj , your stuff regarding strings in java is really great . it is really helpful in prospective of interviews and gaining some knowledge over java strings … Loved it …Keep up good work buddy!!!

              - nandan

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 7, 2013

              Thanks Nandan for kind words. It’s these appreciations that helps me keep going.

              - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 27, 2013

                really this material is gud. definitely it will help a lot 2 give a good concept in string…

                - Trilochan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 7, 2013

                Thanks for liking it.

                - Pankaj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 15, 2013

                  sir pls clearly explain the java in string concept

                  - tamil

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 15, 2013

                  I have already wrote a lot about String class in java, String is like other classes in java with some additional features because of it’s heavy usage. Read these posts for better understanding: https://www.journaldev.com/802/why-string-is-immutable-or-final-in-java https://www.journaldev.com/797/what-is-java-string-pool

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 6, 2013

                    after readind all your questions i realfeel like am getting real basic and clear from all my doubts. pls increase your collections. i read String and COllection and it helped m e

                    - nilesh shinde

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 7, 2013

                    Thanks Nilesh, it really feels good that my articles are helping and cleared your doubts.

                    - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    February 3, 2014

                    its really good and useful…try to post some typical and tricky programs on strings which will be helpful for interviews and thanks…

                    - dinesh

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 5, 2013

                      All your tutorials are great. Helping me in my job jump. Thanks a lot.

                      - devs

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        December 9, 2013

                        Hi pankaj, Thanks a lot for providing examples and good explanations.if you have stuff about GWT framework(Google Web Toolkit) please post that frame work concepts too.it will be really help to for those who new to this framework

                        - senthil hari

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          February 18, 2014

                          Please also put some light on the implementation of substring? How substring method can cause memory leaks? How can we avoid these memory leaks in java?

                          - Ashi

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

                            Please complete your information!

                            Become a contributor for community

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

                            DigitalOcean Documentation

                            Full documentation for every DigitalOcean product.

                            Resources for startups and SMBs

                            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                            Get our newsletter

                            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                            New accounts only. By submitting your email you agree to our Privacy Policy

                            The developer cloud

                            Scale up as you grow — whether you're running one virtual machine or ten thousand.

                            Get started for free

                            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                            *This promotional offer applies to new accounts only.