Is String and StringBuffer both required ?


General J2EE: Is String and StringBuffer both required ?

  1. Is String and StringBuffer both required ? (3 messages)


    Is String and StringBuffer both required ? When manipulating with String, it creates an internal temporary StringBuffer and finally converts it to a String object.
    When StringBuffer is effective in a way to work with both memory and swiftness, then why should we have two classes, String and StringBuffer separately.

    Pls clarify me in this regard.

    Thanks in Advance.

  2. String is a Read Only Class(Same string constatnt is pooled and used by more than one attributes). you can't update String.

    StringBuffer is immutable, you can update it.

    I think in most of the cases we will use String to compare or refer only, in that case pooling will increase the performance.

  3. I think Senthil meant to say that a StringBuffer is mutable :)

    He has it right, thought. Strings are optimized for non-changing, in memory string objects. StringBuffers are optimized for efficient string-manipulation operations. Both classes work best in different situations.

    Typically you will use a StringBuffer to assemble data, then convert it to a String to hold it in memory:

    // Creating an option list from an array ...
    StringBuffer buffer = new StringBuffer();
    for(int i=0; i<options.length; i++) {
    String list = buffer.toString();

    Note that you might be tempted to write code like this:

    // Creating an option list from an array ...
    String list = "";
    for(int i=0; i<options.length; i++) {
       list += "<option>" + options[i] + "</option>";

    This code will be much less effecient, because the JVM will create a new StringBuffer object for each iteration. If you have 20 options, this means 20 StringBuffer objects (and 20 Strings), as opposed to one StringBuffer object and String for the earlier example.
  4. Oops, Sorry for the mistake !