Which is the Best Java Web Framework ?

Java - Interview Questions and Answers on StringBuilder and StringBuffer

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

Ans. java.lang.StringBuffer.

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

Q3.  Difference between StringBuffer and StringBuilder ?

Ans. StringBuffer is synchronized whereas StringBuilder is not.

Q4.  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).

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

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

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

Q10. Which of the two "StringBuilder" or "StringBuffer" is faster and Why ?, 

Ans: StringBuilder is not synchronized and hence faster than StringBuffer.
Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.