DEV Community

Abhinav Pandey
Abhinav Pandey

Posted on • Updated on

JAVA - String and StringBuilder

String

  1. Single copy of each String literal is maintained in String pool.
  2. Since literals are immutable, they can be safely referenced by multiple variables. (interning)
  3. Use variable.intern() to return the literal referenced by the String variable. E.g.
String str2 = str1.intern(); 
Enter fullscreen mode Exit fullscreen mode
  1. Initializing using "new" (not recommended as it will not reuse string pool literals) - E.g.
String str1 = new String("Hello"); // or 
String str2 = new String(charArray); // charArray is character array
Enter fullscreen mode Exit fullscreen mode

String Builder

  1. Mutable.
  2. Extra methods - append, insert, delete, reverse etc.
  3. Instantiated using "new". E.g.
StringBuilder sb = new StringBuilder(); //empty value
StringBuilder sb = new StringBuilder("Hello"); //value is hello
StringBuilder sb = new StringBuilder(10); //value is empty, default capacity(memory reserved) is 10
Enter fullscreen mode Exit fullscreen mode

Capacity is elastic and will increase if more characters are added in the object.
Reading a character beyond current length(no. of characters stored) throws StringIndexOutOfBoundsException.

Top comments (0)