EasyConcept

What is the difference between String, StringBuilder and StringBuffer in Java?

Technology:
Java
Experience:
Intern,
Junior

Quick answer

String is immutable, StringBuilder is a mutable and fast but not thread-safe buffer, and StringBuffer is a mutable buffer with synchronized methods that is thread-safe but slower.

Detailed explanation

Because String is immutable, every concatenation creates a new object, so building text in a loop with += is wasteful. Immutability also makes strings safe to share between threads, cache their hash code and use as HashMap keys, and it is what allows the string pool.

Use StringBuilder for building text in a single thread, which is almost always. StringBuffer is a legacy class from Java 1.0 and is rarely needed, since sharing a builder across threads is uncommon and you usually need your own higher-level synchronisation anyway.

Example

java
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
    sb.append(i).append(',');
}
String result = sb.toString();   // "0,1,2,3,4,"
  • JavaEasy

    What is the difference between JDK, JRE and JVM in Java?

    The JVM runs Java bytecode, the JRE is the JVM plus the standard libraries needed to run Java programs, and the JDK is the JRE plus the development tools such as the compiler (javac).

    Intern 路 Junior 路 Programming Fundamentals
  • JavaEasy

    What is the difference between == and equals() in Java?

    == compares primitives by value and objects by reference (whether they are the exact same object), while equals() compares the logical content of two objects when the class overrides it.

    Intern 路 Junior 路 Programming Fundamentals
  • JavaEasy

    What is the difference between final, finally and finalize in Java?

    final is a keyword that prevents reassigning a variable, overriding a method or extending a class; finally is a block that always runs after try/catch for cleanup; finalize() was a method called by the garbage collector and is now deprecated.

    Intern 路 Junior 路 Programming Fundamentals
  • JavaMedium

    What is the difference between an abstract class and an interface in Java?

    An abstract class can have instance fields, constructors and a mix of implemented and abstract methods but supports only single inheritance, while an interface defines a contract that a class can implement multiple times and, since Java 8, can include default methods.

    Junior 路 Mid-level 路 Object-Oriented Programming