DEV Community

Saurabh Kumar
Saurabh Kumar

Posted on • Edited on

Java StringBuilder Demystified

Let's understand what makes every lead developer say that you should know how to create your own StringBuilder if you plan to modify your strings.
And most of all - what is the difference between string concatenation vs using this pattern.

Simply put what we want to do is - an efficient management of space and performance.

This is the simplest of all the implementations with core characteristics of a StringBuilder

  • .append()
  • .length()
  • .toString()

MyStringBuilder

import java.util.Arrays; public class MyStringBuilder { private static final int INIT_CAPACITY = 16; private static final float LOAD_FACTOR = 0.75f; private static final int MULTIPLIER = 2; private int currentCapacity = INIT_CAPACITY; // store the total number of characters in our string builder private int count; // storage area for our characters private char[] chars; public MyStringBuilder() { chars = new char[INIT_CAPACITY]; } public MyStringBuilder(String str) { this(); append(str); } public MyStringBuilder append(String newStr) { final int length = newStr.length(); // check if resized or not boolean inflated = ensureCapacity(length); if (inflated) { final char[] newBuffer = new char[currentCapacity]; // copy current content System.arraycopy(chars, 0, newBuffer, 0, count); // copy new content System.arraycopy(newStr.toCharArray(), 0, newBuffer, count, length); // update the store array chars = newBuffer; } else { // add the new content to the remaining array space System.arraycopy(newStr.toCharArray(), 0, chars, count, length); } // update the count of chars count += length; return this; } private boolean ensureCapacity(int newLength) { boolean isInflated = false; // ensure the new length is properly accommodated while (Float.compare((float) (count + newLength) / currentCapacity, LOAD_FACTOR) >= 0) { currentCapacity *= MULTIPLIER; isInflated = true; } return isInflated; } public int length() { return count; } @Override public String toString() { return new String(Arrays.copyOfRange(chars, 0, count)); } } public class MyStringBuilderDriver { public static void main(String[] args) { var sb = new MyStringBuilder(); sb.append("Hi").append(" "); sb.append("Saurabh").append(",").append(" "); sb.append("how are you today ?"); System.out.println(sb); System.out.println(sb.length()); } } 
Enter fullscreen mode Exit fullscreen mode

If you feel it's cool - let me know which Java language framework object I should demystify.

Top comments (0)