aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String, StringBuilder, etc Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String, StringBuilder, etc" Watch "String, StringBuilder, etc" New topic
Author

String, StringBuilder, etc

Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
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

Joined: May 26, 2003
Posts: 31079
    
163

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Kevin Florish
Ranch Hand

Joined: Jan 06, 2009
Posts: 176
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.



Java5 Tutorials | Java6 Tutorials | HTML/CSS Tutorials | JavaScript and jQuery Tutorials
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String, StringBuilder, etc