String and StringBuffer, StringBuilder are the classes which operate on strings. Below are the differences:
Point of Distinction | String | StringBuffer | StringBuilder |
---|---|---|---|
Length | Fixed | Increased | Increased |
Mutable | Immutable. if you try to alter their values, another object gets created | Mutable. It can change its value | Mutable. you can add/remove characters, substring without creating new objects. |
Performance | Slower | Faster | Faster |
Memory Consumption | More | Less | Less |
Storage | Constant Pool | Heap Memory | - |
Use | When String not going to change | String change and will be accessed from a multiple thread. | String change and will only be accessed from a single thread. |
Synchronized | - | Yes | No |
Thread Safe | - | Yes. multiple threads can call its method without compromising internal data structure | No |
Efficient | - | Less than StringBuilder | More than StringBuffer |
Example
package com.seleniumtest;
public class StringDifference
{
// Concatenates to String
public static void concateString(String str1)
{
str1 = str1 + " World";
}
// Concatenates to StringBuffer
public static void concateStringBuffer(StringBuffer str2)
{
str2.append(" World");
}
// Concatenates to StringBuilder
public static void concateStringBuilder(StringBuilder str3)
{
str3.append(" World");
}
public static void main(String[] args)
{
String str1 = "Hello";
concateString(str1); // str1 is not changed
System.out.println("String: " + str1);
StringBuffer str2 = new StringBuffer("Hello");
concateStringBuffer(str2); // str2 is changed
System.out.println("StringBuffer: " + str2);
StringBuilder str3 = new StringBuilder("Hello");
concateStringBuilder(str3); // str3 is changed
System.out.println("StringBuilder: " + str3);
}
}
Output
String: Hello
StringBuffer: Hello World
StringBuilder: Hello World
Comments