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 ...
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.