Java J2EE Question and Answers

17. Difference between String, StringBuffer and StringBuilder?
 
  • String is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations – StringBuffer and StringBuilder.
  • StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread safe and synchronized where StringBuilder operations are not thread safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder.
  • StringBuffer performance is fast than StringBuffer because of no overhead of synchronization.
 
Your Name Your Email-ID
Your Answer
18. What does String intern() method do?
 
  • When the intern method is invoked, if the pool already contains a string equal to this string object as determined by the equal (Object) method, then the string from the pool is returned.
  • Otherwise, this String object is added to the pool and a reference to this String object is returned.
  • These method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
 
Your Name Your Email-ID
Your Answer
19. How can we make String upper case or lower case?
 
  • We can use String class to Upper Case and to Lower Case methods to get the String in all upper case or lower case.
  • These methods have a variant that accepts Locale argument and use that locale rules to convert String to upper or lower case.
 
Your Name Your Email-ID
Your Answer
20. What is the difference between StringBuffer and StringBuilder class?
 
  • Use StringBuilder whenever possible because it is faster than StringBuffer.
  • But, if thread safety is necessary then use StringBuffer objects.
 
Your Name Your Email-ID
Your Answer
12345 Page 5 of 5