String FAQ's

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

  • Synchronized → Thread-safe (only one thread can access at a time).
  • Slower compared to StringBuilder due to synchronization overhead.

StringBuilder

  • Not synchronized → Not thread-safe (multiple threads can access simultaneously).
  • Faster than StringBuffer because it doesn’t have synchronization.

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.

  • Heap Memory: Used to store objects and instance variables.
  • Stack Memory: Used to store method calls and local variables.
  • == compares the memory location of two objects.
  • equals compares the contents of two objects.