Strings in Java are immutable, meaning their values cannot be changed after creation. To achieve mutability, you need to use a different data structure. Here are two common approaches:
1. Using StringBuilder
or StringBuffer
:
StringBuilder
andStringBuffer
are mutable classes designed specifically for manipulating strings efficiently.- They provide methods like
append()
,insert()
,delete()
, andreplace()
to modify the string content.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World
2. Converting String to Character Array:
- You can convert a string to a character array using the
toCharArray()
method. - Modify the character array directly, then convert it back to a string using the
String
constructor.
Example:
String str = "Hello";
char[] charArray = str.toCharArray();
charArray[0] = 'J';
String newStr = new String(charArray);
System.out.println(newStr); // Output: Jello
Key Considerations:
StringBuilder
is generally preferred for single-threaded environments due to its performance advantages.StringBuffer
is thread-safe, making it suitable for multi-threaded scenarios.
In summary, while strings in Java are inherently immutable, you can achieve mutability by utilizing StringBuilder
, StringBuffer
, or by manipulating character arrays. Choose the approach that best suits your needs and the specific use case.