In java, the value of a String is fixed after the String is created; Strings are immutable, or unchangeable. When you write someString=”Hello”; and follow it with someString=”Goodbye”; you have nerither changed the contents of computer memory at the address represented by someString nor eliminated the characters “Hello”. Instead, you have stored “Goodbye” at a new computer memory location and stored the new address in the someString variable. If you wan to modify someString from “Goodbye” to “Goodbye Everybody”, you cannot add a space and “Everybody” to the someString that contains “Goodbye” Instead, you must create an entirely new String,”Goodbye Everybody”, and assign it to the someString address.
To circumvent these limitations, you can use either the StringBuilder or StringBuffer class. You use one of these classes, which are alternatives to the String class, when you know a String will be modified; Usually, you can use a StringBuffer or StrinBuilder object anywhere you would use a String. Like the String class, these two classes are part of the java.lang package and are automatically imported into every program. The classes are identical except for the following:
StringBuilder is more efficient.
StringBuffer is thread safe. This means you should use it in applications that run multiple threads, which are paths of control taken during program execution.
You can create a StringBuilder object that contains a String with a statement such as the following:
StringBuilder message = new StringBuilder(“Hello there”);
A StringBuilder object, contains a memory block called a buffer, which might or might not contain a string. Even if it does contain a string, the string might not occupy the entire buffer. In other words, the length of a string can be different from the length of the buffer. The actual length of the buffer is the capacity of the StringBuilder object.
You can change the length of a string in a StringBuilder object with the setLength() method. When you increase a StringBuilder object’s length to be longer than the String it holds, the extra characters contain “\u0000”. If you use the setLength() method to specify a length shorter than its String, the string is truncated.
Using StringBuilder objects provides improved computer performance over String objects because you can insert or append new contents into a StringBuilder. In other words, unlike immutable Strings, the ability of StringBuilders to be modified makes them more efficient when you know string contents will change.