Results 1 to 19 of 19

Thread: when we use String and StringBuffer?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Contributing Member
    Join Date
    Sep 2006
    Answers
    962

    when we use String and StringBuffer?

    Can anybody explain me when to use String and when the StringBuffer in an application? and Which one is better?

    ------------------
    suresh


  2. #2
    Junior Member
    Join Date
    Jul 2007
    Answers
    1

    Re: when we use String and StringBuffer?

    hai,
    String:Is Used, when length of the string entered shouldnt change.
    StringBuffer:Is used in case of varying length of string.


  3. #3
    Junior Member
    Join Date
    Jul 2007
    Answers
    3

    Re: when we use String and StringBuffer?

    Strings are immutable ie. once they are defined they cant be changed. so when you know that the data you are defining is going to change or get modified, aty that time you can use Strinmg Buffer.


  4. #4
    Junior Member
    Join Date
    Jul 2007
    Answers
    4

    Re: when we use String and StringBuffer?

    String is immutable whereas StringBuffer and StringBuilder can change their values.

    The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

    Criteria to choose among String, StringBuffer and StringBuilder

    1. If your text is not going to change use a string Class because a String object is immutable.
    2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
    3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.


  5. #5
    Junior Member
    Join Date
    Oct 2007
    Answers
    1

    Arrow Re: when we use String and StringBuffer?

    Quote Originally Posted by psuresh1982 View Post
    Can anybody explain me when to use String and when the StringBuffer in an application? and Which one is better?

    ------------------
    suresh
    String is immutable .it means that we can not change the state of string object.we use string when we reqire string which we never want to change.
    the object of string is just read only dear.bt it is very simple as for coder point of view
    and about string buffer ,it is mutable we can change the state .its not just a read only .we can use concatination better in string buffer case.string buffer hav better performance than string class.


  6. #6
    Junior Member
    Join Date
    Jul 2007
    Answers
    20

    Re: when we use String and StringBuffer?

    we cannot change any value in the string.
    But we easily change any value at String Buffer.

    we cannot insert, delete any values at string.
    But we can insert new elements and also delete any elements from the
    String Buffer.

    So, If we want to delete or insert any elements when execution means we use StringBuffer.

    I will send Explain later....

    By Kaliswaran
    My emailid is kaliswaranbsc @ gmail . com
    any Query means send to me....


  7. #7
    Junior Member
    Join Date
    Sep 2007
    Answers
    7

    Thumbs up Re: when we use String and StringBuffer?

    Hi,

    First of all you should understand that String is immutable and StringBuffer is Mutable. That is You cannot append something to a String Object (No append method is there for String.). When you try to do that, JVM will ignore the first Object and create a new Object with new value.
    eg: String s = "Midhun";
    s = s + " Thomas";
    Now the Object "Midhun" will be ignored and new object with the value "Midhun Thomas" will be created. Then JVM will make the object reference 's' point to the second string. The first String "Midhun" is now eligible for garbage collection.

    But in the case of StringBuffer, there is a method called append(), that will allow you to append anything to an existing StringBuffer object. So No memory wastage will be there.
    eg: StringBuffer s1 = new StringBuffer("Midhun");
    s1.append(" Thomas");
    Here, No new Object is getting created, The string " Thomas" is just getting appended to "Midhun".

    Now you try to guess when to use String and when to use StringBuffer ......................... YES YOU ARE RIGHT............................>


    Use StringBuffer when you would have to make so many changes to a String Object. Otherwise use String. StringBuffer is slower than String because all methods in StringBuffer are Synchronized.
    If you want to get all he advantages of StringBuffer without this disadvantage, Use StringBuilder. It allows you to append and its methods are not synchronized also. So it is as fast as String.

    ptmidhun @ gmail . com


  8. #8
    Junior Member
    Join Date
    Sep 2007
    Answers
    3

    Re: when we use String and StringBuffer?

    Hi....

    If you want to store a string but don't need to modify that string in your program then you should use String. But if you want to store as well as want to modify that string value in the program then you've store that in a StringBuffer type variable. Because you can't modify a String type variable, StringBuffer type is modifiable. That's all, please let me known if it's clear to you now.

    Thanks,

    Kuntal


  9. #9
    Expert Member
    Join Date
    Oct 2007
    Answers
    375

    Smile Re: when we use String and StringBuffer?

    Hi,

    Both String and StringBuffer classes are provided by Java.
    Difference is that Objects returned by String class are read only and immutable.

    But StringBuffer class represents characters that can be modified.

    Also stringBuffer class is faster as compared to String class while performing simple perations like concatenation.

    Instance - using String Class , String str = new String("Hello")
    str += "world"

    But a stringBuffer would use -

    StringBuffer str = new StringBuffer("Hello")
    str.append("World")

    though second appears complex, it uses lesser bytecodes and completes faster.


  10. #10
    Junior Member
    Join Date
    Jan 2007
    Answers
    22

    Re: when we use String and StringBuffer?

    the one basic difference between String and StringBuffer classes is that
    if you change the value of an object referred to by String it will create a new object (so u will end up with two String object if u modify a string) however in case of StringBuffer it is not the case you can modify the same StringBuffer and in the background also there is only one StringBuffer .
    -thanks.


  11. #11
    Junior Member
    Join Date
    Jul 2007
    Answers
    20

    Re: when we use String and StringBuffer?

    String:
    Strings are represented a sequence of characters. The Easist way to represent a sequence of character in JAVA is by using Character Array.
    Some String Methods:
    sn=so.toLowerCase; // convert so to all Lowercase letters
    sn=so.toUpperCase;// Convert so to all UpperCase letters
    sn.Length()// gives the length of sn
    sn.Concat(so);// Concatenates so and sn

    String Buffer:
    String Create of fixed_length. String Buffer Creates String of flexible lenght that can be modified in terms of both length and constent.
    we can insert characters and substrings in the middle of a string or append another string to the end of string Buffer. But we cannot do any of this in the String.

    String Buffer methods:
    so.setCharAt(n,'x');//modifies nth Character to x.
    sn.append(so);//Appends string so to end of sn
    s1.insert(n,s2);//Inserts String s2 at position n of String s1.


  12. #12
    Junior Member
    Join Date
    Oct 2007
    Answers
    4

    Re: when we use String and StringBuffer?

    String
    String is immutable: you can’t modify a string object but can replace it by creating a new instance. Creating a new instance is rather expensive.

    //Inefficient version using immutable String
    String output = “Some text”
    Int count = 100;
    for(int I =0; i<count; i++) {
    output += i;
    }
    return output;

    The above code would build 99 new String objects, of which 98 would be thrown away immediately. Creating new objects is not efficient.


    StringBuffer / StringBuilder
    StringBuffer is mutable: use StringBuffer or StringBuilder when you want to
    modify the contents.
    StringBuilder was added in Java 5 and it is identical in StringBuffer except that it is not synchronised, which makes all respects to it slightly faster at the cost of not being thread-safe.

    //More efficient version using mutable StringBuffer
    StringBuffer output = new StringBuffer(110);
    Output.append(“Some text”);
    for(int I =0; i<count; i++) {
    output.append(i);
    }

    return output.toString();

    The above code creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer expands as needed, which is costly however, so it would be better to initilise the StringBuffer with the correct size from the start as shown.

    Another important point is that creation of extra strings is not limited to 'overloaded mathematical operators’ (“+”) but there are several methods like concat(), trim(), substring(), and replace() in String classes that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better performance.


  13. #13
    Junior Member
    Join Date
    Feb 2008
    Answers
    1

    Re: when we use String and StringBuffer?

    your string buffer works
    but inspite "return" change it as a "System.out.println(output.toString())"
    so it will be error free pgm


  14. #14
    Junior Member
    Join Date
    Aug 2007
    Answers
    1

    Re: when we use String and StringBuffer?

    i have a question up here

    If we can do everything with StringBuffer then why do we still have String?

    Thanks
    vijay


  15. #15
    Contributing Member
    Join Date
    Nov 2007
    Answers
    46

    Re: when we use String and StringBuffer?

    String:
    strings are always using new object for every modification.but no modifications are allowed on the original instance.
    StringBuffer:
    this is immutable. the changes will be occured on the same instance.
    my comment:
    better to use StringBuffer,which contains some more mothods,those are not applied on the String instance


  16. #16
    Junior Member
    Join Date
    Feb 2008
    Answers
    1

    Re: when we use String and StringBuffer?

    Helo freinds ...

    A very good explanation regarding strings and string buffers so far as per my knowledge i will explain immutability and mutablity. Strings are immutable right?? then why did java people made them immutable...???

    the concept of strings in java is little tricky as it maintain separate pool in memory. Pool??? its known as string pool whenever we create object using constructor like boy b=new boy();

    jvm creates a "boy" object in garbage collectable heap and assigns "b" varaible to it .every body knows this ... But with strings there will be two ways of object creation 1. String s1=new string("hello"); ---> same story of object creation stated above. 2. String s1="hello"; --> this is a type of object creation especially with strings. When jvm sees any text between " " and if the text is referenced by a string variable jvm creates a string object and it will place the object in string pool.

    Now many of my freinds stated above that if we dont need to change the length of text we need to go to strings . Why is it so??? suppose say i have a string pool object string s1="hello"; steps taken by jvm when it sees above code...: 1.create hello object in pool. 2.assigns s1 variable pointing to "hello". Now at a later point of time some where in your code if you want to make a same string "hello". But you dont know that already same string exists in memory we will write string s2="hello";

    now instead of creating new object in string pool jvm first checks for any exisiting objects with same content.if it founds any objects rather than creating a new one it will point new reference to existing object i.e. Now "hello" is referenced by two variables s1 & s2.

    Now think for a while that there is no concept of immutability in java at some other point of time if we change s1 to some other value then automatically s2 will also change as they both refer to same object . So to avoid this confusion java people made strings immutable i think it became a big lesson now...

    so im stopping it here right now... For furthur quiries regarding java just mail me to gkrishna.java@gmail.com

    Last edited by admin; 02-12-2008 at 11:20 AM.

  17. #17
    Junior Member
    Join Date
    May 2008
    Answers
    8

    Re: when we use String and StringBuffer?

    since strings are immutable and due to its cannonical representation ,we use strings
    any where in java.while coming to stringbuffer we have to instantiate for every time we are using.
    for ex,
    String s="java is a programing language";//cannonical form
    StringBuffer sb=new StringBuffer("java is a programing language");//normal form


  18. #18
    Junior Member
    Join Date
    Oct 2008
    Answers
    3

    Re: when we use String and StringBuffer?

    Hi,
    String has a behaviour such that if you declare the String like
    String str1 = "shakthi"; This will have immutable behaviour means it will save in a String constant pool and works like a normal literal. String str = new String("shakthi"); is just like our normal object, which is waged. The same even with StringBuffer. In real time scenarios, StringBuffer will be taken for performance consideration, that is say you have a list of records with which you have to form a String.
    The code will be
    String test = "";
    for(int i=0;i<list.size();i++){
    test = test + list.get(i).toString();
    // Keep in mind here abandoned objects are going to form because
    //every time String objects will be immutable, say the list contains 3 Strings
    //["devathi", " shakthi", " kumar"], now for first iteration test
    //will become "devathi" for the next iteration it becomes "devathi shakthi",
    //but an abandoned object for "devathi" will be still remained in the String
    //Constant pool, because "devathi" is String which cannot be immutable
    }
    The compensation for the above issue is going for a StringBuffer
    StringBuffer test = new StringBuffer();
    for(int i=0;i<list.size();i++){
    test.append(list.get(i).toString());
    }
    Also, note that if performance is an issue, means if your system or application is very slow, it is not advisable to go for StringBuffer because StringBuffer is synchronized. Keeping this into consideration Sun developers intoduced StringBuilder into jdk1.5. It provides the same functionality with asynchronous behaviour. Hope i have provided an useful information.
    Thanks,
    Shakthi Kumar.D


  19. #19
    Junior Member
    Join Date
    Nov 2008
    Answers
    1

    Re: when we use String and StringBuffer?

    String concatenation (+) internally uses StringBuffer.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.
Interact