Java - Interview Questions and Answers on Strings

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 class 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.  how many objects are created with this code ?

String s =new String("abc"); 

Ans. Two objects will be created here. One object creates memory in heap with new operator and second in stack constant pool with "abc".

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