String vs StringBuilder vs StringBuffer

Tushar Ghosh
2 min readNov 4, 2022

--

Working with JavaScript 6+ years. Recently, I have started my MS degree. Here Java is the mandatory course. So I have started to learn Java. String is the most import class in Java. When to use which class that makes application faster or slower. After finishing this article, you can learn the proper use of String class.

String:

  • String is immutable which means if you assign value it will not be changed but reference can be changed.
  • If string value is not changed frequently, It is okay to use.
  • String is comparatively slow.

StringBuilder:

  • StringBuilder is mutable.
  • StringBuilder is not thread safe.
  • SingleBuilder is fast in single thread environment

StringBuffer:

  • StringBuffer is also mutable.
  • SingleBuffer is thread safe.
  • Multiple thread can not access the StringBuffer simultaneously.
  • It comparatively slow than Stringbuilder but faster than String.

Object Creation:

String instance can be created two different way:

  • String literal
  • New operator
// By String literal.
String str = "Hello World";
// By new operator.
String str2 = new String("Hello World");
String name = "Tushar";
boolean equal = name.equals("Tushar"); //true
boolean refEqual = (name == "Tushar"); //true, but be careful
String newName = new String("Tushar");
refEqual = (newName == "Tushar"); //false!
refEqual = (newName.equals("Tushar")); //true

// == tests for reference equality (whether they are the same object).
// .equals() tests for value equality (whether they contain the same data).

String Pool: The String class maintains in heap memory a table of Strings that have been “interned”. When a string literal is defined, the table is checked; if the string already exists, it is returned, otherwise it is added to the table.

String s = "Bob"; //string literal, placed in String pool
String t = new String("Bob"); //not placed in String pool

System.out.println(s==t); //not identical strings
//System.out.println(s.equals(t));
t = t.intern(); //now it is forced into the String pool

System.out.println(s==t);

//moral: the string literal "Bob" is created by (new String("Bob")).intern() )

StringBuilder and StringBuffer can be created using only new operator:

StringBuffer sb = new StringBuffer("Hello World");
StringBuilder sbl = new StringBuilder("Hello World");

References:

  1. https://medium.com/quick-code/what-is-the-difference-between-string-stringbuilder-and-stringbuffer-6b8a998f6eae
  2. https://stackoverflow.com/questions/21375659/is-new-string-immutable-as-well (***)
  3. https://www.scientecheasy.com/2022/01/difference-between-string-stringbuffer-stringbuilder.html/
  4. https://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html#axzz7javuOUIA

--

--

Tushar Ghosh
Tushar Ghosh

Written by Tushar Ghosh

MEAN | JavaScript | Node.js | React| Angular | Frontend

No responses yet