Classe StringBuffer et StringBuilder en Java

Both StringBuffer and StringBuilder are two important classes in Java which represents mutable String i.e. the String object, whose value can be changed. Since String is Immutable in Java, any change or operation on String object e.g. converting it to upper or lower case, adding character, removing a character, or getting a substring, all results in a new String object.

Anyway, when StringBuffer was introduced it has its own problem e.g. it was synchronized, methods like append have synchronized and hence they were slower. Even if you use them by just one thread and don’t share with other threads, the cost of acquiring and releasing lock due to Synchronization is still significant.

Since StringBuffer is mostly used as local mutable String variable making it synchronized wasn’t a great decision and Java designer realized their mistake and corrected it in Java 1.5 by introducing the StringBuilder class.

As I have said that both StringBuffer and StringBuilder are a mutable alternative of String class and you can change the content without creating additional objects. With String example program in java

Here are some more key differences between StringBuilder and StringBuffer in Java:

  1. StringBuffer is present in Java and StringBuilder was added in Java 5.

  2. Both StringBuffer and StringBuilder represents mutable String which means you can add/remove characters, substring without creating new objects.

  3. You can convert a StringBuffer into String by calling toString() method.

  4. Both StringBuilder and StringBuffer doesn’t override equals() and hashCode() method because they are mutable and not intended to be used as a key in hash-based collection classes e.g. HashMap, Hashtable, and HashSet.

  5. StringBuffer is synchronized which means all method which modifies the internal data of StringBuffer is synchronized e.g. append(), insert() and delete(). On the contrary, StringBuilder is not synchronized.

  6. Because of synchronization StringBuffer is considered thread safe e.g. multiple threads can call its method without compromising internal data structure but StringBuilder is not synchronized hence not thread safe.

  7. Another side effect of synchronization is speed. Since StringBuffer is synchronized its lot slower than StringBuilder.

  8. The default length of StringBuffer is 16 characters. You should explicitly define the size of it, especially if you know that size would be less or more than 16 to avoid wasting memory and spending time during resize.

  9. In general, you should always use StringBuilder for String concatenation and creating dynamic String unless and until you are absolutely sure that you need StringBuffer.

  10. The string concatenation done using + (plus) operator internally uses StringBuffer or StringBuilder depending upon which Java version you are using. For example, if you are running in Java 5 or higher than StringBuilder will be used and for the lower version, StringBuffer will be used.

Related blog:

Spring boot interview questions

Recommended Posts

Classe StringBuffer et StringBuilder en Java
[Java] Différence entre StringBuffer et StringBuilder
À propos de la classe Java StringBuilder
Java --StringBuilder vs StringBuffer
Définition et instanciation de classe Java
[Java] À propos de String et StringBuilder
Différence entre StringBuilder et StringBuffer
Ecrire une classe en Kotlin et l'appeler en Java
Utilisation correcte de la classe abstraite et de l'interface en Java
[Java] Gestion des chaînes de caractères (classe String et classe StringBuilder)
Implémentez Thread en Java et essayez d'utiliser la classe anonyme Lambda
Exemple d'encodage et de décodage en Java
Implémentez l'interface Java dans la classe JRuby et appelez-la depuis Java
Comprendre equals et hashCode en Java
Bonjour tout le monde en Java et Gradle
Mécanisme et caractéristiques de la classe d'implémentation Collection souvent utilisés en Java
Qu'est-ce qu'une classe en langage Java (3 /?)
[Java] Différences entre les variables d'instance et les variables de classe
Qu'est-ce qu'une classe en langage Java (1 /?)
Qu'est-ce qu'une classe en langage Java (2 /?)
[Java] Comparaison des méthodes d'opération de la collection et de StringBuilder
Programmation Java (clause statique et "variables de classe")
Création d'une classe de matrice dans Java Partie 1
Différence entre les listes d'arry et les listes liées en Java
Programmer les en-têtes et pieds de page PDF en Java
Apprenez les modèles Flyweight et ConcurrentHashMap en Java
La direction de Java dans "C ++ Design and Evolution"
De Java à C et de C à Java dans Android Studio
Lire et écrire des fichiers gzip en Java
Différence entre int et Integer en Java
Discrimination d'énum dans Java 7 et supérieur
Méthodes de classe Java
Classe et modèle
[Java] Héritage de classe
classe Scanner java
Partition en Java
Classe Java HashMap
java (classe abstraite)
Changements dans Java 11
Janken à Java
[Java] Classe imbriquée
Classe anonyme Java
À propos de la classe Java
Java et JavaScript
XXE et Java
[java] Classe abstraite
Taux circonférentiel à Java
[Java] Classe d'objets
Classe locale Java
FizzBuzz en Java
GetInstance () à partir d'une classe @Singleton dans Groovy à partir de Java
Concernant les modificateurs transitoires et la sérialisation en Java
[Java] Comment utiliser la classe FileReader et la classe BufferedReader
Détecter des vidéos similaires dans Java et OpenCV rev.2
Appel de méthode Java depuis RPG (appel de méthode dans sa propre classe)
Traitement parallèle et parallèle dans divers langages (édition Java)
Différence entre next () et nextLine () dans Java Scanner