Java - Interview Questions and Answers on String , StringBuilder and StringBuffer

Q1.  Difference between == and .equals() ?

Ans. "equals" is the member of object class which returns true if the content of objects are same whereas "==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

Q2.  Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object?

Ans. java.lang.StringBuffer.

Q3.  What will this code print ?

String a = new String ("TEST");
String b = new String ("TEST");

if(a == b) {
       System.out.println ("TRUE");
} else {
       System.out.println ("FALSE");
}

Ans. FALSE.

== operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content.

Q4.  What is a String Pool ?

Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created 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.

Q5.  Why is String immutable in Java ?

Ans. 1. String Pool

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode

If string is not immutable, One can change its hashcode and hence not fit to be cached.

3. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.

Q6.  What is the difference between StringBuffer and String class ?

Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.

Q7.  What is an immutable class ?

Ans. Class using which only immutable (objects that cannot be changed after initialization) objects can be created.

Q8.  Difference between StringBuffer and StringBuilder ?

Ans. StringBuffer is synchronized whereas StringBuilder is not.

Q9.  Explain the scenerios to choose between String , StringBuilder and StringBuffer ?

Ans. If the Object value will not change in a scenario use String Class because a String object is immutable.

If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).

If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

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

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

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

Q12.  Write a method that will remove given character from the String?

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

Q13.  Which String class methods are used to make string upper case or lower case?

Ans. toUpperCase  and toLowerCase

Q14.  How to convert String to byte array and vice versa?

Ans. We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

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

Q16.  Why String is popular HashMap key in Java?

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

Q17.  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 1
          System.out.println(s3.hashCode()==s4.hashCode()); Output 2
     }
}

What will be the Output 1 and Output 2 ?

Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.

Q18.  What is the use of HashCode in objects ?

Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.

Q19.  What does String intern() method do?

Ans. intern() method keeps the string in an internal cache that is usually not garbage collected.

Q20.  How substring() method of String class create memory leaks?

Ans. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. Hence you can inadvertently keep a reference to a very big character array with just a one character string.

Q21.  Write a program to reverse a string iteratively and recursively ?

Ans. Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

public static String getReverseString(String str){
      StringBuffer strBuffer = new StringBuffer(str.length);
      for(int counter=str.length -1 ; counter>=0;counter--){
            strBuffer.append(str.charAt(counter));
      }
      return strBuffer;
}

Recursive -

public static String getReverseString(String str){
      if(str.length <= 1){
          return str;
      }
      return (getReverseString(str.subString(1)) + str.charAt(0);
}

Q22.  What will the following code print ?

String s1 = "Buggy Bread";
String s2 = "Buggy Bread";
if(s1 == s2)
     System.out.println("equal 1");
String n1 = new String("Buggy Bread");
String n2 = new String("Buggy Bread");
if(n1 == n2)
     System.out.println("equal 2");

Ans. equal 1

Q23.  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. true, due to String Pool, both will point to a same String object.

Q24.  what will be the output of this code ?

public static void main(String[] args)
{
      StringBuffer s1=new StringBuffer("Buggy");
               test(s1);
      System.out.println(s1);
}

private static void test(StringBuffer s){
s.append("Bread");
}

Ans. BuggyBread

Q25.  what will be the output of this code ?

public static void main(String[] args)
{
      String s1=new String("Buggy");
               test(s1);
      System.out.println(s1);
}

private static void test(StringBuffer s){
s.append("Bread");
}

Ans. Buggy

Q26.  what will be the output of this code ?

public static void main(String[] args)
{
      StringBuffer s1=new StringBuffer("Buggy");
               test(s1);      
      System.out.println(s1);
}

private static void test(StringBuffer s){
s=new StringBuffer("Bread");
}

Ans. Buggy

Q27.  Which methods of the Pattern class have equivalent methods in the String class?

Ans. split() and macthes()

Q28.  public class BuggyBread1{

    public static void main (String args[]) {
     Set<String> mySet = new TreeSet<String>();
     mySet.add("1");
     mySet.add("2");
     mySet.add("111");
     for(String d: mySet){
      System.out.println(d);
     }
    }
}

Ans. 1
111
2

TreeSet maintains the elements in the ascending order which is identified by the compareTo method. compareTo method in String has been defined such that it results in the natural alphabetic Order. Here the elements in the TreeSet are of String and not of Integer. In String Natural Order, 111 comes before 2 as ascii of 1st character first determines the order.