Results 1 to 17 of 17
  1. #1
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Objects in String and StringBuffer

    How many objects are created in Code 1 in each line and also in Code 2 in each line? How is StringBuffer better when compared to String?

    Code 1:
    Java Code:
    1. String output = “Some text”
    2. Int count = 100;
    3. for(int i =0; i<count; i++) {
    4. output += i;
    5. }
    6. return output;
    Code 2:
    Java Code:
    1. StringBuffer output = new StringBuffer(110);// set an initial size of 110
    2. output.append(“Some text”);
    3. for(int i =0; i<count; i++) {
    4. output.append(i);
    5. }
    6. return output.toString();

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,352
    Blog Entries
    7
    Rep Power
    20

    Default Re: Objects in String and StringBuffer

    In line #4 of the first example the following objects are created:

    1) a temporary StringBuilder (or StringBuffer)
    2) a String representation of variable 'i'
    3) a String representation of the StringBuilder.

    In line #4 of the second example, only a String representation of variable 'i' is created.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Objects in String and StringBuffer

    What do you think is the answer?
    Otherwise we might just think you're dumping your homework here...

    Besides, I hate these things...I mean, we don't know how many objects are created for some of those lines as the constructor of (eg) the StringBuffer may be (and I expect is) creating objects for its attributes.

    Or am I overthinking things again?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: Objects in String and StringBuffer

    Quote Originally Posted by Tolls View Post
    Or am I overthinking things again?
    Probably, as these questions (whether homework or exam) are usually only worried about the "main" objects, i.e. the StringBuffer and String object creations. They never care to know about the char arrays, and ints, for example, that are part of the String and StringBuffer objects.

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    Looks like the homework question here is to actually explain why StringBuffer/StringBuilder may actually be a slightly better choice when building a larger String; it isn't so much about the exact number of objects created, just to realize and explain that listing one will in fact create many more objects than listing 2.

    I'm not going to give the answer to that, it would defeat the purpose of the homework question. Try to find a possible explanation first and then we can discuss how much of it is true.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,388
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    Is it a reasonable requirement for some to have to know how the compiler generates byte codes for various constructs? It used to be that compilers from different vendors would generate different code. It would all execute but some generated code would be better than others. And no one could be expected to know from architecture to architecture what the generated machine code would look like.

    But even with a virtual architecture there could be differences in generated byte code between different vendor implementations. Or have the Java specifications eliminated that and dictated how code should be compiled?

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: Objects in String and StringBuffer

    The actual byte code can still vary, somewhat, but the behaviour is fairly strictly defined, so the differences SHOULD be VERY minor.

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,352
    Blog Entries
    7
    Rep Power
    20

    Default Re: Objects in String and StringBuffer

    The only thing the JLS has to say about it is this:

    Quote Originally Posted by JLS
    15.18.1.2 Optimization of String Concatenation

    An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
    For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,388
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    The reason I ask is that this is the second time in a week that a question has come up regarding how the code is compiled. The first was why one uses int and not short or byte in for loops. I had to write some examples and look at the compiled byte codes to realize that there are special instructions for handling int types that make it more efficient. Had I not done this I would not have known the answer.

    I used to program in Digital Equipment Corporations PDP/11 assembly language. It had identical instructions for both bytes and ints. So no performance improvement would necessarily be gained using one over the other. And I would never have been asked a similar question about a C compiler because it depended on the architecture. So it seems that one must know much more about the internals of Java to be an expert Java programmer than would be required to be an expert C (or its variants) programmer.

    Regards,
    Jim
    Last edited by jim829; 09-17-2013 at 04:20 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    Quote Originally Posted by jim829 View Post
    The reason I ask is that this is the second time in a week that a question has come up regarding how the code is compiled. The first was why one uses int and not short or byte in for loops. I had to write some examples and look at the compiled byte codes to realize that there are special instructions for handling int types that make it more efficient. Had I not done this I would not have known the answer.
    Okay, but you won't notice that difference unless you're doing some massively CPU heavy code. Better not to worry about such internal details until you need to. And by extension: better not make novices aware of such internal details, because there is already too much of a tendency to want to do premature optimizations.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,388
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    I agree entirely. I just wanted to see if I could determine why the int based for loop was preferable. Remember -- this was from an earlier post and was supposedly asked as an interview question (which I personally believe is an unreasonable question). If there is another, less anal answer to the question I would like to know. I would have probably answered it wrong.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  12. #12
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    IMO - it is unreasonable to ask it in general. In very specific areas of interest, namely gaming & simulation and real time processing or other performance intensive applications, then it surely helps a whole lot to know how Java ticks under the hood. As an extreme example: I've seen people tuning their application such that a garbage collection was only triggered once at night in a window in which the application was allowed to be unresponsive for an hour. You can't get that done unless you dig in deep.

    But in the general case you have to write dumb code and let the Java compiler and runtime optimizer do its thing. Not making use of the Java platform features basically defeats the purpose of using Java after all. Forgetting about byte and short and always using int is nice and dumb in my book :)

    Long story short: nowadays I would actually encourage to not know too much about it; the less you know, the less chance you'll have of throwing a wrench into the machine that is Java.
    Last edited by gimbal2; 09-17-2013 at 05:16 PM.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  13. #13
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Objects in String and StringBuffer

    This is not a homework question.

    Anyways my take on this

    Code 1:
    Java Code:
    String output = “Some text”
    Int count = 100;
    for(int i =0; i<count; i++) {
    output += i;
    }
    return output;
    In code 1:
    in line 1, one object is created
    in line 4, hundred objects are created(from 0-99)
    Total:101 objects are created

    Code 2:
    Java Code:
    StringBuffer output = new StringBuffer(110);// set an initial size of 110
    output.append(“Some text”);
    for(int i =0; i<count; i++) {
    output.append(i);
    }
    return output.toString();
    In code 2:
    in line 1 one object is created
    Total: 1 object is created.

    Pls correct me if I am wrong

    BTW is there a difference between int and Int?
    Last edited by suhaas_mohandos; 09-18-2013 at 08:40 AM.

  14. #14
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default Re: Objects in String and StringBuffer

    Quote Originally Posted by suhaas_mohandos View Post
    In code 1:
    in line 1, one object is created
    I maybe wrong but I believe it is 2. "some text" is created and placed in the String Literal Pool and a String object which references that literal is created and placed in the normal object heap.

    BTW is there a difference between int and Int?
    Try compiling the second one.

  15. #15
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Objects in String and StringBuffer

    Quote Originally Posted by suhaas_mohandos View Post
    This is not a homework question.
    It may not be homework, but it is certainly a homework question. Lets replace homework with "quiz" : nothing changes, the purpose is that you think about it and provide your own vision. Judging by what you've given now, I see you've got the right idea.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  16. #16
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,352
    Blog Entries
    7
    Rep Power
    20

    Default Re: Objects in String and StringBuffer

    Quote Originally Posted by suhaas_mohandos View Post
    In code 1:
    in line 1, one object is created
    in line 4, hundred objects are created(from 0-99)
    Total:101 objects are created
    That is not correct; see my reply #2.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Objects in String and StringBuffer

    Quote Originally Posted by Junky View Post
    I maybe wrong but I believe it is 2. "some text" is created and placed in the String Literal Pool and a String object which references that literal is created and placed in the normal object heap.
    Nope.
    No objects are created on that line.
    A reference to the object in the String Literal Pool containing "some text" is assigned to that String variable.
    The pool already exists.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. ArrayList + String/StringBuffer
    By Army in forum New To Java
    Replies: 3
    Last Post: 04-17-2012, 08:28 PM
  2. String vs. StringBuilder vs. StringBuffer
    By stchman in forum New To Java
    Replies: 5
    Last Post: 01-12-2012, 07:52 AM
  3. Easiest way to convert String to StringBuffer
    By unideal in forum New To Java
    Replies: 4
    Last Post: 12-13-2009, 12:43 PM
  4. Replies: 3
    Last Post: 03-04-2009, 06:03 AM
  5. Replies: 1
    Last Post: 03-03-2009, 05:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •