O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.4. Mutable Strings

String objects cannot be changed, but you have been creating strings that are combinations and modifications of existing String objects, so how is this done? Java has two other standard classes that encapsulate strings, the StringBuffer class and the StringBuilder class, and both StringBuffer and StringBuilder objects can be altered directly. Strings that can be changed are referred to as mutable strings, in contrast to String objects that are immutable strings. Java uses objects of the StringBuffer class type internally to perform many of the operations that involve combining String objects. Once the required string has been formed as a StringBuffer object, it is then converted to an object of type String.

You have the choice of using either a StringBuffer object or a StringBuilder object whenever you need a string that you can change directly, so what's the difference? In terms of the operations these two classes provide, there is no difference, but StringBuffer objects are safe for use by multiple threads, whereas StringBuilder objects are not. You'll be learning about threads in Chapter 16, but in case you're not familiar with the term, threads are just independent execution processes within a program that can execute concurrently. For example, an application that involves acquiring data from several remote sites could implement the data transfer from each remote site as a separate thread. This would allow these relatively slow operations to execute in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required