• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings concat()

 
Ivan Ivanoff
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dear ranchers,
String s = "please help"; //1
s.concat(" me!"); //2
System.out.print(s); //3
Why it prints "please help" without " me!" ?
I kind of know that if I change line //2 to be like s = s.concat(" me!") then it will create brand new String object & output will be
"please help me!".
So what is the reason to use
conctat() method without creating brand new String object like i have on line //2 ???
Any help would we great !
thx
 
Kareem Qureshi
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan,
Because strings are immutable, a new string is created everytime we try to modify it.So in your case s.concat("me") creates a new string object and s still remains the same.
Hope this helps
Kareem
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic