• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

StringBuilder and substring()

 
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah OK, thanks for that guys.
 
Bartender
Posts: 1251
87
Hibernate jQuery Spring MySQL Database Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic