Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String and StringBuffer roundup

 
Tom Tang
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The == and equals() for String and StringBuffer have been haunting me for quite a while. This is why I prepare the following codes to clear up. I think it might help other people as well. You can also refer to the following thread for a good discussion. http://www.javaranch.com/ubb/Forum24/HTML/006874.html

I don't what it will look like after posting, but it looks good in my Textpad.
Thanks.

}
 
Cherry Mathew
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Tom
correct me if im wrong
i think if an object is created at compile time then it goes into the string pool and if the object is created at runtime a new object is created that is the reason why when a String literal is used in '+' it creates one in pool instead of creatinga new object. and if u use a function it tries to return the same string if it can for example when we call concat with an empty string and trim() without empty spaces.
Thank u for compiling the code
Cherry
 
Tom Tang
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are absolutely right. When you say s1==s1.trim(); it returns true. The compiler just knows that you are doing nothing.

from Jane:
When you create a String using new or when the String is the result of a runtime operation Java creates a new object.
If the String is a literal; the result is placed in a 'string pool'. If the the String already exists in the pool, a reference to the pre-existing string is returned by the compiler.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic