String, StringBuilder, StringBuffer
String
- Immutable class
- Thread Safe
- It is a final class
When we create a String using double quotes, JVM first looks for the String with the same value in the string pool. If found, it returns the reference of the string object from the pool. Otherwise, it creates the String object in the String pool and returns the reference. JVM saves a lot of memory by using the same String in different threads.
If the new operator is used to create a string, it gets created in the heap memory.
Whenever we do String manipulation like concatenation, substring, etc. it generates a new String and discards the older String for garbage collection. These are heavy operations and generate a lot of garbage in heap.
StringBuffer or StringBuilder is used for string manipulation
StringBuilder
- Mutable class
- Not thread safe
- Faster
StringBuffer
- Mutable class
- Thread safe
- Slower
Comments
Post a Comment