Java StringBuilder

March 2, 2018 Oclemy Java StringBuilder, Java String 0 minutes, 55 seconds

Java provides us with an intuitive way of creating and working with sequence of characters that can be modified.

StringBulilder as class derives from AbstractStringBuilder.

public final class StringBuilder extends AbstractStringBuilder {}

It implements java.io.Serializable and java.lang.CharSequence.

public final class StringBuilder extends AbstractStringBuilder implements Serializable, CharSequence {}

StringBuilder resides in the java.lang package.

package java.lang;

Creating a StringBuilder.

StringBuilder provides several constructors to instantiate it.

No. Constructor Description
1. public StringBuilder() Instantiates a StringBuilder with an initial capacity of 16.
2. public StringBuilder(int capacity) Instantiates a StringBuilder with the specified capacity.
3. public StringBuilder(CharSequence charsequence) Instantiates a StringBuilder with the contents of the specified CharSequence.
4. public StringBuilder(String myString) Instantiates a StringBuilder with the contents of the specified String.

Example.

StringBuilder sb=new StringBuilder();

Appending Items to a StringBuilder

Items can be added to a StringBuilder object using the append() method.

sb.append("Mercury");
sb.append("Venus");
sb.append("Earth");

Chaining StringBuilder methods

Most of the methods in the StringBuilder return this so that the method calls can be chained together in a fluent manner.


sb.append("Mercury").append("Venus").append("Earth").append("Mars");

Comments