Java - Interview Questions and Answers on String Pool

Q1.  What is a String Pool ?

Ans. String pool (String intern pool) is a special storage area in Java heap. When a string literal is referred and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

Q2.  What are different ways to create String Object? Explain.

Ans. 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.


Q3.  Why Char array is preferred over String for storing password?

Ans. String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.

Q4. What will be the output of following Code ?

class BuggyBread {
    public static void main(String[] args)
    {
         String s2 = "I am unique!";
         String s5 = "I am unique!";

         System.out.println(s2 == s5);
    } 

}

Ans. Output will be true, due to String Pool, both will point to a same String object.

Q5. What will be the output of following Code ?

class BuggyBread {
    public static void main(String[] args)
    {
         String s2 = new String("I am unique!");
         String s5 = new String("I am unique!");

         System.out.println(s2 == s5);
    } 

}

Ans. Output will be false, as they are two different objects. String Pool won't be referred here.

Q6. 

public class a {
    public static void main(String args[]){
       final String s1="job";
       final String s2="seeker";
       String s3=s1+s2;
       String s4="jobseeker";
       System.out.println(s3==s4); // Output
    }
}


What will be the Output ?

Ans. Here it will store S1,S2 and S3 in String Pool. For S4 it will look in String pool and will find a match with S3 and hence will store the same reference. Output will be true.

Q7. 

public class a {
    public static void main(String args[]){
       final String s1="job";
       final String s2="seeker";
       String s3=s1.concat(s2);
       String s4="jobseeker";
       System.out.println(s3==s4); // Output
    }
}


What will be the Output ?

Ans. Here it will store the concatenated string in a new String object and hence Output will be false.