• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Concatenate->Print OR System.out.print() ???

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm a little confused. In situations where a loop is necessary. Is it better to concatenate strings then print? Or print as you go?
Which is a better use of resources?
 
Ranch Hand
Posts: 3143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would say print as you go because each time you concatonate you create a new String object.
Somebody will probably argue with me though.
 
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with Angela. Do your concatenation outside of the loop and then use the loop to print.
 
Ranch Hand
Posts: 351
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've found the nitpicking to be very consistent on this topic.
Print as you go will be greatly favored over concatenating. Why? As Angela said, every time you concatenate two Strings a new String Object is created.
Strings are immutable so a new String has to be created to hold the result of the concatenation. If you experiment with this you'll find very quickly that application performance can be greatly enhanced by minimizing String concatenations.
[ April 08, 2002: Message edited by: Michael Pearson ]
 
Sheriff
Posts: 4012
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another vote for printing as you go. If I remember correctly, for every concatenation there's a String and a StringBuffer object that get created (for each String to be concatenated??) - I could be wrong on that.
There's another discussion on it here:
(Don't worry about the broken image links, the substance is still there.)
http://www.javaranch.com
Have fun Josue

(Marilyn fixed link)
[ July 18, 2002: Message edited by: Marilyn de Queiroz ]
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually, every time you concatenate Strings, four(4) objects are created.
 
Matthew Phillips
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Would you please elaborate on the 4 objects? I had heard this before, but I haven't seen an explanation.
 
Chicken Farmer ()
Posts: 1932
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not like I really need to say it, but ditto to everyone's posts.
In regards to the four objects, take this example:
String s1 = "Hello " + "world";
This equals (if what I have read from all my searches on the web is correct):
StringBuffer buffer = new StringBuffer().append( new String( "Hello " ) ).append( new String( "world" ) );
String s1 = buffer.toString();
So you have the two new String() objects, and the two buffer objects ( one new StringBuffer() and one returned from append()).
 
Michael Pearson
Ranch Hand
Posts: 351
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When 2 Strings are concatenated a StringBuffer is created and multiple append() methods are called.
Example:
String str1 = "cat";
String str2 = "tail";
String str3 = str1 + str2 ;
For str3 to be initialized with the value "cattail" the following happens in the background:
new StringBuffer().append( str1 ).append( str2 );
 
jason adam
Chicken Farmer ()
Posts: 1932
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So when concating these two strings, your 4 objects are 3 buffers (one for new StringBuffer() and then one for each append) and then the final String object ( from toString() )?
Whichever way, easy to see just how crazy iterative concats can get.
 
Michael Pearson
Ranch Hand
Posts: 351
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since StringBuffers are mutable appending does not create new Objects.
new StringBuffer().append( str1 ).append( str2);
The 4 Objects in my example are:
  • String str1
  • String str2
  • the anonymous StringBuffer
  • str3


  • -----
    If the result of the concatenation is sent to output instead of assigned to String str3 it will still take 4 Objects. The StringBuffer is converted to a String before it is printed.
    this code
    system.out.println( str1 + str2 );
    causes this:
    system.out.println( new StringBuffer.append( str1 ).append( str2).toString() ) );
    (? This may be done with an implicit cast. I'm using the toString method as pseudo code. )
    [ April 08, 2002: Message edited by: Michael Pearson ]
     
    Marilyn de Queiroz
    Sheriff
    Posts: 9109
    12
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    How many Objects are created here?


    A StringBuffer object is created and within that a char[] object. Then a String object
    is created and within that a char[] object.
    Four objects.
     
    Michael Pearson
    Ranch Hand
    Posts: 351
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    That's a good example. You cleared up my misconception.
     
    Ranch Hand
    Posts: 133
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    In the case of Java 1a and 1b, it's better to print as you go. However, you're usually not printing the string immediately. Often, you're creating a string which you will pass to another method or return. In those cases, it's best to create a StringBuffer and use .append().
     
    whippersnapper
    Posts: 1843
    5
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Now here's a question:
    I know StringBuffer.append() doesn't create a new StringBuffer object. But ultimately that call results in System.arraycopy() doing the work.
    System.arraycopy() is a native method, so there's no Java code to investigate. The API documentation says that it "copies" from the source array to the destination array. But what if the destination array isn't big enough? Within Java code, arrays aren't resizable, right? So does arraycopy() have the ability to behind-the-scenes increase the size of an array, or is it creating a new char[] array whenever the destination array isn't big enough?
    If it is creating a new char[] array as a result of the StringBuffer.append(), then that brings up the count of objects to 5 for a typical concatenation.
     
    jason adam
    Chicken Farmer ()
    Posts: 1932
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Michael Pearson:
    Since StringBuffers are mutable appending does not create new Objects.
    [ April 08, 2002: Message edited by: Michael Pearson ]



    Good catch, thanks! Was thinking that since it returns a StringBuffer, it's returning a new one. Was still thinking of String, where something like substring() actually returns a new String.
     
    jason adam
    Chicken Farmer ()
    Posts: 1932
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    And based on what I see happening in append() and expandCapacity(), I don't see how you could have an array that is smaller than what you are appending, if I understand the question correctly.
     
    Michael Pearson
    Ranch Hand
    Posts: 351
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Michael Matola:
    Now here's a question:
    But what if the destination array isn't big enough? Within Java code, arrays aren't resizable, right? So does arraycopy() have the ability to behind-the-scenes increase the size of an array, or is it creating a new char[] array whenever the destination array isn't big enough?


    I didn't have any way to express this as well as it is in the J2SE API:
    Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.
    I interpret that to mean a new object is made in the background.
    FYI - default length for a new StringBuffer() is 16 characters.
     
    Pauline McNamara
    Sheriff
    Posts: 4012
    6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Marilyn deQueiroz:
    How many Objects are created here?


    A StringBuffer object is created and within that a char[] object. Then a String object
    is created and within that a char[] object.
    Four objects.


    Didn't quite follow here.
    Does String s1 = "a" ; not create an object?
    Are "a" and "b" each String objects with a char[] object within?
    This looks like one of those certification questions.
     
    jason adam
    Chicken Farmer ()
    Posts: 1932
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    This looks like one of those certification questions.[/QB]


    This actually deals with more of a dig down implementation detail than what the cert. deals with. So you're safe
     
    Michael Pearson
    Ranch Hand
    Posts: 351
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    A String is a reference variable. Right now you are hitting your forehead because you know the rest of the answer to your question.
    Strings are special reference variables in Java. In the background a String object references a char array. Fortunately you just get to declare a String and the overhead is taken care of.
    [ April 09, 2002: Message edited by: Michael Pearson ]
     
    Marilyn de Queiroz
    Sheriff
    Posts: 9109
    12
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Pauline, "a" is a String literal object, but it is not a new object created by concatenation. We are talking only about the new objects that are made due to the concatenation.

    Michael, a String is an immutable Object consisting of a sequence of characters. It is not a char[] like it is in C/C++, although you can create a char[] with a method in the String class. In fact, I had a question regarding this on my SCJP exam. In fact, you can create a String object from a char[], you can create a String object from a byte[], you can create a String object from a StringBuffer, but a String object is none of these.
     
    Michael Pearson
    Ranch Hand
    Posts: 351
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks for the correction. I thought my anology was pretty good when I wrote it, but on the second read it's not.
    learning curve, ouch!
    [ April 09, 2002: Message edited by: Michael Pearson ]
     
    Pauline McNamara
    Sheriff
    Posts: 4012
    6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks all.
    Marilyn could you elaborate on your example please?
    I'm feeling kind of dense right now because I still don't get this part of what you said: "and within that a char[] object".
    [ April 10, 2002: Message edited by: Pauline McNamara ]
     
    Marilyn de Queiroz
    Sheriff
    Posts: 9109
    12
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Pauline, do you know how to look at the source code for the java.lang package? You can see in the concat() method of the java.lang.String class how it works.
    [ April 10, 2002: Message edited by: Marilyn deQueiroz ]
     
    You showed up just in time for the waffles! And this tiny ad:
    Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    reply
      Bookmark Topic Watch Topic
    • New Topic