Placeholder Image

Subtitles section Play video

  • Here's a summary of what we just learned.

  • A string is immutable, which means it can't change once it's been created.

  • You have to create a brand new string object if you want a slightly

  • different string.

  • On the other hand, a StringBuilder is also a sequence of characters, but

  • it is mutable.

  • So it can change after you've created it.

  • Now, there are pros and cons of when to use each one.

  • But if you're trying to build up a longer text string gradually over

  • several steps, then StringBuilder is a much more efficient data type,

  • because it is mutable.

  • Otherwise, if you had to create a new string object at each intermediate step,

  • you'd be wasting memory on the device.

  • And those additional memory allocations would need to be cleaned up once those

  • string objects were no longer used.

  • It's much cleaner to have a single StringBuilder object and

  • then modify it as needed.

  • Okay, so let's look at the code for how to use the StringBuilder class.

  • We can declare and instantiate a new StringBuilder as usual, and

  • then proceed to put the word,

  • world spelled W-O-R-L-D into the builder using the append method.

  • Now, the StringBuilder is currently holding the sequence of characters

  • that spells world.

  • Actually, let's make that say word

  • instead of world by removing the L character at position three.

  • When we do this the builder now contains the characters W-O-R and D, or word.

  • Then the code appends more characters on the StringBuilder.

  • First, we add space builder and then finally a period.

  • Note that the append method returns a builder object, so what's neat

  • is that we can actually have multiple calls to append on a single line.

  • This sequence of multiple meta calls on a single line is known as method

  • chaining in programmer speak.

  • So as you can see, the second time we call append, we can add a period.

  • When we're done building we can get a frozen immutable string

  • by simply calling the two string method.

  • So as we finish we can see that the String variable built

  • now contains the contents word builder.

Here's a summary of what we just learned.

Subtitles and vocabulary

Click the word to look it up Click the word to find further inforamtion about it