Tags

Feb 20, 2012

Frequently Asked Question about strings



Q: Why is String class immutable?

Ans: As string objects are used the most hence to avoid placing synchronization blocks at every place where multiple threads should not access string object simultaneously, String class was made immutable
Q: What is the difference between String, StringBuffer and StringBuilder?
Ans: String is immutable. StringBuffer provides immutability but has synchronized methods and StringBuilder class has similar features as StringBuffer but has non-synchronized methods
Q:What is the difference between a String object created on String pool and on the heap? Or What will be the result of following statements?
1) “abc” == “abc”
2) new String(“abc”) == new String(“abc”) 
Ans: The second object created with same content using String literal means both are pointing to same object in pool. But if created using new operator then each one takes new memory space even if they have same characters
 Q: Which new feature has been added to JDK 7 regarding Strings?
Ans: Strings can now be used in Switch/Case statements
Q: What happens when concatenation operator is used with Strings as shown in 1 and 2 below:
1) String str1 = “abc”;
String str2 = “def”;
String str3 = str1 + str2;
2) String str4 = “abc” + “def”;
Ans:  1) doesn’t result in such optimization and hence creates more number of String objects 
2)results in compiler optimization and hence the statement becomes String str4 = “abcdef”; after compilation




No comments:

Post a Comment