A String in Java is a sequence of characters inside double quotes and is used to represent text.
A String is immutable because once it's created, its value cannot be changed.
Literal String:
- Stored inside heap memory (string pool or string constant).
- Shares memory if the same value (duplicate value) already exists.
Non-Literal String:
- Stored in heap memory.
- Creates new memory every time, even if the value is the same.
Immutable String:
- Can store duplicate values in the same memory.
- Cannot change the value in memory.
- In concatenation, must create new memory.
Mutable String:
- Cannot store duplicate values in the same memory.
- Can change the value in memory.
- In concatenation, takes the same memory.
The String class is immutable. So frequent modifications (like loops, concatenations) create new objects, reducing performance.
StringBuffer and StringBuilder are mutable, so they provide better performance in scenarios involving frequent string changes.
StringBuffer vs StringBuilder
StringBuffer
StringBuilder
A special memory area in the heap where string literals are stored. When a string literal is created, Java checks the pool. If it exists, it reuses it. If not, it creates and stores it in the pool. Helps with memory optimization.
Signup