Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

System.out.print vs. String concantenation

 
Pat Barrett
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic