Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

StringBuilder and substring()  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys, I have an interesting example aken from the OCA book, quite confusing for me I have to admit.
OK, so here is the code:

Right, this is the way I thought I'd have solved it.
sub essentially contains 'anim', but what I thought was that this  would have had an effect even on sb itself, changing its value from "animals" to "anim", reason being there is only one StringBuilder object which isn't immutable so I don't need to store its reference anywhere: a bit as if I would have done this  sb.append("b"), which would have changed the string to "animalsb" presumably?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The substring method of class StringBuilder does not change the StringBuilder, so you're wrong about the last part.

It just returns a substring of the content of the StringBuilder, in a String. See the API documentation: StringBuilder.substring(int start, int end)
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The JavaDoc is probably your best resource here ... see here. Notice that the documentation does *not* state that the substring() method has any effect on the current StringBuilder value.

Henry
 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah OK, thanks for that guys.
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason as you are dealing with String concepts, you can have a look at Storage of Strings - The String Literal Pool will clear all your doubts regarding String If there is any
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!