aspose file tools*
The moose likes Cattle Drive and the fly likes System.out.print vs. String concantenation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "System.out.print vs. String concantenation" Watch "System.out.print vs. String concantenation" New topic
Author

System.out.print vs. String concantenation

Pat Barrett
Ranch Hand

Joined: Jan 03, 2001
Posts: 63
Hello,
I've finally gotten the nitpicks for 1.4 whittled down to where I'm requested to write directly to the console as opposed to tracking a String variable. Is using System.out.print/println always preferrable to concantenating a String?
Thanks in advance,
Pat B.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
I had the same problem. I think it causes more overhead to the program to collect all of these strings and keep adding to them. Since strings are immutable, with each concatenation, you are creating another string for the pool. So in that case, I would at least use a StringBuffer, but after I went through the program the correct way, it was even easier to not pass anything around, and just print directly to the screen.
Bill
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9052
    
  12
>I think it causes more overhead to the program to collect all of
>these strings and keep adding to them. Since strings are
>immutable, with each concatenation, you are creating another
>string for the pool.

Not only are you creating a new immutable string with each concatenation, you are creating several objects each time you concatenate, and object creation is costly.

Besides, the key with using System.out.print/println vs. string concatenation is that with the concatenation, you will end up doing both!

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: System.out.print vs. String concantenation