Let's learn some Java string interview questions and answers in this article


1)What are the different ways to create string objects?

String objects can be created in two ways –

1. Using the ‘new’ operator

2. Using double-quotes

String s1 = new String (“java”);

String s2 = “java code”;

When the String is created with the double quotes, JVM searches it for in the string constant pool. If the same value is found, it returns the reference to that String else it creates a new object with the new value provided.

In the other case, if the String is created with the “new” operator, then JVM creates a new object but not in the string pool. If we want create the object in the string pool, we can use the intern() method.

2)What is a string constant pool?

The memory space allocated in the heap memory to store the string literals is called the string constant pool.

No two string objects can have the same value in a string constant pool. String pool is used to store unique string objects.

When you try to assign the same string literal to different string variables, JVM saves only one copy of the String object in the String constant pool, and String variables will start referring to that string object.


String Constant Pool


3)Why is Java provided with String constant pool as we can store the objects in heap memory?

String constant pool provides the facility of reusability of the existing string objects.

When a new string object is created using the string literals, then JVM first checks in the pool if this String already exists or not.

If it exists, then it will reference the existing String rather than creating a new object.

This will help in the speeding up of the application and helps in saving the memory as no two objects will have the same content.


4)How many objects are created in the following code snippet?

String s1 = new String (“java”);

Most of us says 1? its wrong. Its 2

1 in heap and another one in String constant pool


5)How many objects are created in the following code snippet?

String s1 = “java”;

String s2 = new String (“java”);

Two objects are created in the above code snippet.

s1 String is created in the string constant pool as it is created by string literals.

s2 String is created in heap memory as it is created by the “new” operator. No new object will be created in the string constant pool as it is already created by s1.


6)How many objects are created in the following code snippet?

String s1 = new String (“java”);

String s2 = new String(“java”);

Three objects will be created.

For string s1, two objects will be created, one in heap memory and the other in string constant pool.

For string s2, only one object will be created in heap memory, but no new object will be created in the string constant pool as the object with same value is already present in the string constant pool.


7)How to compare two strings in java?

We can compare  two strings using the equals() method, == operator and compareTo() method.

When we compare strings using the equals() method, we are comparing the content of the strings, whether these strings have the same content or not.

String s1 = new String(“java”);

String s2 = “java”;

System.out.println(s1.equals(s2)); // returns true ( value comparison)


When we compare strings using the == operator, we are comparing the reference of the string, whether these variables are pointing to the same string object or not.

String s1 = new String(“java”);

String s2 = “java”;

System.out.println(s1==s2); // returns false (reference comparison)


Also, we can compare string lexicographically (comparing strings by alphabetical order). We can use the compareTo() method to compare the strings lexicographically.

compareTo() method returns a negative integer, 0, or a positive integer.

firstString.compareTo(secondString)

It will return a negative integer, if firstString is less than the secondString.

i.e firstString < secondString → returns a negative integer


If firstString is equal to the secondString it will return zero.

 i.e firstString == secondString → returns zero


If firstString is greater than the secondString, it will return a positive integer. 

i.e firstString > secondString → returns a positive integer


Try to avoid using '==' operator method to compare two string values.


8)What does the string intern() method do?

The task of the intern() method is to put String (which is passed to the intern method) into the string constant pool.

When the intern method is invoked, if the String constant pool already contains a string equal to the String object as determined by the equals(Object) method, the String from the pool is returned.

Otherwise, the String object is added to the pool, and a reference to the String object is returned.

String s1= “java”;

String s2 = new String(“java”);

String s3 = s2.intern();

System.out.printls(s1 == s3); // returns true

System.out.printls(s2 == s3); // returns false


9)Why is string made immutable in JAVA?

Immutable means unmodifiable or unchangeable

Security is the major reason why strings in Java are made to be immutable. Strings in Java can be used to access data sources like files, databases, pr even objects found across networks. Even sometimes, strings store passwords and usernames, which can’t be modified once created.


10)Write a code in java to prove that String objects are immutable?

String s1 = “java”;

// Print s1 hash code


S1 = s1 + “code”;

//print s2 hash code


11. What is the difference between the String and StringBuffer?

The String is a final class in Java. The String is immutable. That means we can not change the value of the String object afterword.

Since the string is widely used in applications, we have to perform several operations on the String object. Which generates a new String object each time, and all previous objects will be garbage object putting the pressure on the Garbage collector.

Hence, the Java team introduced the StringBuffer class. It is a mutable String object, which means you can change its value.

The string is immutable, but the StringBuffer is mutable.

To know more about String Buffer and String Builder 

12. What is the difference between the StringBuffer and StringBuilder?

We know String is immutable in Java. But using StringBuffer and StringBuilder, you can create editable string objects.

When Java Team realizes the need for the editable string object, they have introduced the StringBuffer class. But all the methods of the StringBuffer class are synchronized. That means at a time, only one thread can access a method of the StringBuffer.

As a result, it was taking more time.

Latter, Java Team realizes that making all methods of the StringBuffer class synchronized was not a good idea, and they introduced a StringBuilder class. None of the methods of the StringBuilder class are synchronized.

Since all the methods of the StringBuffer class are synchronized, StringBuffer is thread-safe, slower, and less efficient as compared to StringBuilder.

Since none of the methods of the StringBuilder class is synchronized, StringBuilder is not thread-safe, faster, and efficient as compared to StringBuffer.

13. What is the format() method in Java String? What is the difference between the format() method and the printf() method?

format() method and printf() method both format the string. The only difference is that the format() method returns the formatted string, and the printf() method prints the formatted string.

So when you want the formatted string to use in the program. you can use the format method. And when you want to just print the formatted string, you can use the printf() method.

14. Can you say String is ‘thread-safe’ in Java?

Yes, we can say that the string is thread-safe.

As we know, String is immutable in Java. That means once we created a string, we can not modify it afterword. Hence there is no issue of multiple threads accessing a string object.


15. Why most of the time string is used as HashMap key?

The string is immutable. So one thing is fixed that it will not be changed once created.

Hence the calculated hashcode can be cached and used in the program. This will save our effort for calculating the hashcode again and again. So, a string can be used efficiently than other HashMap key objects.

16. Can you convert String to Int and vice versa?

Yes, you can convert string to int and vice versa.

You can convert string to an integer using the valueOf() method and the parseInt() method of the Integer class.

Example -

String str = "1234";

// convert string to int using Integer.parseInt() method

int parseIntResult1 = Integer.parseInt(str);

// convert string to int using Integer.valueOf() method

int valueOfResult1 = Integer.valueOf(str);


Also, you can convert an integer to string using the valueOf() method of the String class.

Example - 

int number = 789;

// convert integer to string using String.valueOf() method

String valueOfResult2 = String.valueOf(number);


17. What is the split() method?

The split method is used to split the string based on the provided regex expression.

The Signature of the split method is

public String[] split(String regex)

This method will return an array of the split substrings.

Example -

public class JavaSplitExample {

public static void main(String[] args) {

String name = "Welcome, to, NGEducate";

String [] substringArray = name.split(",");

for(String substring : substringArray) {

    System.out.print(substring);

}

}

}

The output of the above program will be

Welcome to NGEducate

18. What is the difference between "NGEducate".equals(str) and str.equals("NGEducate")?

Both look the same, and it will check if the content of the string variable str is equal to the string "NGEducate" or not.

But their behaviour will change suddenly when a string variable str = null. The first code snippet will return false, but the second code snippet will through a NullPointerExpection.

Below I have given a program which uses both ways to compare string using equals() method.


/*

 * A Java program which checks

 * both ways of string comparison using equals() method.

 *

 * This program throws a NullPointerException at second print statement.

 */

public class StringExample {

public static void main(String[] args) {

String str = "Gaurav Kukade";

System.out.println("Gaurav Kukade".equals(str)); // true

System.out.println(str.equals("Gaurav Kukade")); // true

}

}

The output of the above program will be

true

true

It is true both times because the content of both strings is equal to each other.


Now, we will check a program where the str=null

/*

 * A Java program which checks

 * both ways of string comparison using equals() method.

 * 

 * This program throws a NullPointerException at second print statement.

 */

public class StringNullExample {

  public static void main(String[] args) {

      String str = null;

      System.out.println("Gaurav Kukade".equals(str)); // false

     System.out.println(str.equals("Gaurav Kukade")); // NullPointerException

 }

}

The output of the above program will be

false

Exception in thread "main" java.lang.NullPointerException


We can see the above output, for first code snippet it is print false but for the second code snippet, it is throwing NullPointerException.

It is one of the most important tricks to avoid the null pointer exception in java string. So this question is important.


19. Can we use a string in switch case in java?

Yes, from Java 7 we can use String in switch case.

Below, I have given a program that shows the use of the string in switch case.


/*

 * A Java program showing the use of

 * String in switch case.

 */

public class StringInSwitchExample  

    public static void main(String[] args) 

    { 

        String str = "two"; 

        switch(str) 

        { 

            case "one": 

                System.out.println("January"); 

                break; 

            case "two": 

                System.out.println("February"); 

                break; 

            case "three": 

                System.out.println("March"); 

                break; 

            default: 

                System.out.println("Invalid month number"); 

        } 

    } 

}

The output of the above program will be

February


20. How string concatenation using the + operator works in Java?

+ operator is the only overloaded operator. You can use it for both adding two numbers as well as for string concatenation purposes.

If you are using the Java version 1.5 or above, string concatenation internally uses the append() method of the StringBuilder. And for versions lower than 1.5, it uses the append() method of the StringBuffer class.


21. What is the use of StringJoiner?

StringJoiner is a Java class that allows you to construct or create a sequence of strings (characters) that are separated by delimiters like a hyphen(-), comma(,), etc. Optionally, you can also pass suffix and prefix to the char sequence.


Example: -

// importing StringJoiner class  

import java.util.StringJoiner;  

public class ExampleStringJoiner

{  

   public static void main(String[] args) 

   {  

       StringJoiner joinStrings = new StringJoiner(",", "[", "]");

       // passing comma(,) and square-brackets as delimiter   

         

       // Adding values to StringJoiner  

       joinStrings.add("learn");  

       joinStrings.add("java");  

       joinStrings.add("strings"); 

                  

       System.out.println(joinStrings);  

   }  

}

Output: 

[learn,java,strings]


22. How can a Java string be converted into a byte array?

The getBytes() method allows you to convert a string to a byte array by encoding or converting the specified string into a sequence of bytes using the default charset of the platform. 

Below is a Java program to convert a Java String to a byte array.

Example:

import java.util.Arrays;
public class StringToByteArray 
{
   public static void main(String[] args)         
   {
      String str = "Scaler";
     byte[] byteArray = str.getBytes();

      // print the byte[] elements
     System.out.println("String to byte array: " + Arrays.toString(byteArray));
   }
}

Output:

String to byte array: [83, 99, 97, 108, 101, 114]