- Java has 3 basic classes used to manipulate strings:
- String
- StringBuffer
- StringBuilder
- When comparing any type of string, remember that == checks if the objects refer to the same memory.
- Use the equals() method to compare if two strings have the same value.
- Strings are compared using lexigraphical order - for instance, the letters A-Z come "before" the letters a-z.
String
-
The String class is the basic class for storing and manipulating strings.
-
Objects of class String are:
- interned, meaning they are stored in a string table, and the JVM manages whether or not copies are made, in other words, it may use references.
- immutable, meaning that the String class does not provide any way in which to change a String object once it has been created.
- String literals, also called string constants, are of class String. For instance, these give the same logical result:
if (str1.equals("abc"))
if ("abc".equals(str1))
StringBuilder
- The StringBuilder class is used to store dynamic strings, in other words, strings that are modifiable.
- A StringBuilder object has an initial amount of space, and if the capacity is exceeded, it is increased automatically.
StringBuffer
- The StringBuffer class is also used to store dynamic strings, but has the added advantage over StringBuilder in that it is thread-safe (more on this later).
- Of course the advantage adds extra processing, so StringBuilder is more efficient in single-threaded code.
When to use String and when to use StringBuilder/StringBuffer?
Use the String class for values that do not change. Use StringBuilder or StringBuffer for values that change, or for code that frequently builds strings, for instance with concatenation.