Strings in Java are of two types:
1️⃣ Mutable Strings – These strings can be changed after creation.
2️⃣ Immutable Strings – These strings cannot be changed after creation.
Mutable Strings in Java
Mutable strings are strings that can be changed after they are created. In Java, mutable strings are handled using StringBuffer and StringBuilder classes.
Different Ways to Create Mutable Strings
Using StringBuffer:
StringBuffer sb = new StringBuffer("java");
Using StringBuilder:
StringBuilder sb = new StringBuilder("java");
Key Differences Between String, StringBuffer, and StringBuilder
Feature | String (Immutable) | StringBuffer (Mutable) | StringBuilder (Mutable) |
---|---|---|---|
Thread-Safe | Yes | Yes | No |
Performance | Slow (New object created every time modified) | Moderate (Synchronized) | Fast (Not synchronized) |
Mutability | No | Yes | Yes |
Immutable Strings in Java
Immutable strings are strings that cannot be changed or modified after they are created. In Java, immutable strings are created using the String class.
Different Ways to Create Immutable Strings
Using a character array:
char name[] = { 'j', 'a', 'v', 'a' }; String s = new String(name);
Using string literals:
String s = "java";
Using the new keyword:
String s = new String("java");