Java Interview QuestionsNo Comments

Java Strings

1. Why Strings are immutable?

String literals are stored in String pool. If a new string is created which already exists, the existing String will be reused. If Strings were mutable, then changing the String with one reference would lead to the wrong value for the other references.

Helps in caching and fast retrieval.

Strings are great candidates for Hashcode(keys) or HashSet. Being immutable guarantees that hashcode will always be the same so that it can be cached, with no need to re-calculate hashcode everytime retrieval is done.

String parameters are used for database connections(username/password), network connection, files etc. Immutability guarantees that the parameters cannot be changed.

Classloaders use String. Immutability guarantees that always correct class is loaded.

Immutability makes String thread-safe. Synchronization overhead is not required.

 

2. Are all String’s immutable?

Value of a String Object once created cannot be modified. Any modification on a String object creates a new String object.

String str3 = "value1";
str3.concat("value2");
System.out.println(str3); //value1

Note that the value of str3 is not modified in the above example. The result should be assigned to a new reference variable (or same variable can be reused). All wrapper class instances are immutable too!

String concat = str3.concat("value2");
System.out.println(concat); //value1value2

 

3. Where are string values stored in memory?

Approach 1
In the example below we are directly referencing a String literal.

String str1 = "value";

This value will be stored in a “String constant pool” – which is inside the Heap memory. If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.


String str5 = "value";

In above example, when str5 is created – the existing value from String Constant Pool is reused.

Approach 2
However, if new operator is used to create string object, the new object is created on the heap. There will not be any reuse of values.

String str2 = new String("value");

 

4. What are differences between String and StringBuffer?

• Objects of type String are immutable. StringBuffer is used to represent values that can be modified.
• In situations where values are modified a number to times, StringBuffer yields significant performance benefits.
• Both String and StringBuffer are thread-safe.
• StringBuffer is implemented by using synchronized keyword on all methods.

 

5. What are differences between StringBuilder and StringBuffer?

StringBuilder is not thread safe. So, it performs better in situations where thread safety is not required.