Java vs C++ String Mutability
Mutability means whether a string's contents can be changed in place without creating a new
object. Java and C++ handle this very differently.
Java Strings: - Immutable: Once created, the value cannot be changed. - Any modification results
in a new string object being created. - Example:
public class Main {
public static void main(String[] args) {
String name = "Cat";
// name[0] = 'B'; // ■ Not allowed
name = "B" + name.substring(1); // Creates a new string "Bat"
System.out.println(name); // Output: Bat
}
}
C++ std::string: - Mutable: You can directly modify characters in the string. - Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Cat";
name[0] = 'B'; // ■ Allowed
cout << name; // Output: Bat
}
StringBuilder & StringBuffer in Java: - These are mutable alternatives to String. - Use them
when you need to modify strings frequently. - StringBuilder: Faster, but NOT thread-safe. -
StringBuffer: Thread-safe (synchronized), but slower. - Example (StringBuilder):
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Cat");
sb.setCharAt(0, 'B'); // Modify in place
System.out.println(sb); // Output: Bat
}
}
Example (StringBuffer):
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Cat");
sb.setCharAt(0, 'B'); // Modify in place
System.out.println(sb); // Output: Bat
}
}
Summary: - Java's String is immutable → modifications create new objects. - Use StringBuilder or
StringBuffer for mutable behavior. - C++ std::string is mutable and allows direct character
modification.