Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String, StringBuilder, etc

 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a C++ developer , I am doing my nest to understand about Strings, and I have some questions...

1. Why would the method substring(int begin, int end) of the class String has the first parameter be 0-based index and the second parameters be 1-based index???

2. Why/when would you use String over StringBuilder, and vice versa?

3. I understand that the class String will create abandoned objects, but won't the Garbage Collector handle that in the background?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34195
340
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) I don't know. I'm sure there was a reason the API designers went that route.
2) You use StringBuilder when appending to a string multiple times.
3) Yes. But this wastes resources. If I am concatenating large strings very quickly, I'm using a ton of memory. Holding everything up to let the garbage collector run can greatly slow things down.
 
Kevin Florish
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rachel Glenn wrote:As a C++ developer , I am doing my nest to understand about Strings, and I have some questions...
1. Why would the method substring(int begin, int end) of the class String has the first parameter be 0-based index and the second parameters be 1-based index???


I think the reason this was done is because you get the length of the substring by subtracting the 1st index from the second. Here's the speel from the Ofiicial String docs:

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic