# String
- String is immutable
String
class usesfinal
keyword, so no class can inherit it- it doesn't have any method to modify the string
- String is treated as a const, it's thread safe
- Whenever you do strig concatenation, appending one string to the end of the string (uses + operator), it actually creates a new
String
object, and then point to theString
object.
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { | |
private final char value[]; //... } |
use "+" operator or StringBuilder?
Use StringBuilder
when a mutable string is needed
# StringBuffer
- It's thread safe because it is
Synchronized
- It has methods
append
,insert
,indexOf
etc.
# StringBuilder
- It's not thread safe, not
synchronized
- It has methods
append
,insert
,indexOf
etc.
# Summary
String
is immutableStringBuilder
andStringBuffer
are mutable- use
String
if you don't need to handle too much data - use
StringBuilder
in single-thread if you have to deal with lots of data - use
StringBuffer
in multi-thread if you have to deal with lots of data