Menu
Topics Index
...
`


Strings >
Siva Nookala - 20 Feb 2017
StringBuilder is a mutable sequence of characters and this class is compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

The methods and usage of them in StringBuilder class is same as in the String Buffer class. Refer to the links below to know them in detail.

Java StringBuffer , Java StringBuffer length() And capacity() Methods, Java StringBuffer ensureCapacity() Method With Example, Java setLength() Method In StringBuffer Class, Java charAt() And setCharAt() Methods in StringBuffer, StringBuffer getChars() Method In Java With Example, Java append() Method In StringBuffer, Java StringBuffer insert() Method With Example, Java StringBuffer, reverse() - Reverse A String In Java, Java delete() and deleteCharAt() Methods In StringBuffer, Java StringBuffer replace() Method With Example, Java substring and Additional StringBuffer Methods In Java .

StringBuilderDemo
class StringBuilderDemo
{
    public static void main(String[] args) {
    
        StringBuilder sb = new StringBuilder("Merit"); // LINE A
        System.out.println("StringBuilder = " + sb);
    
        // appends the string argument to the StringBuilder
        sb.append(" Campus"); // LINE B
        // print the StringBuilder after appending
        System.out.println("After append = " + sb);
    
        // insert string value at offset 0
        sb.insert(0, "Java "); // LINE C
    
        // prints StringBuilder after insertion
        System.out.print("After insertion = " + sb);
    
    }

}
OUTPUT

StringBuilder = Merit
After append = Merit Campus
After insertion = Java Merit Campus

DESCRIPTION

First "Merit" is taken into StringBuilder. Using append method, " Campus" is appended to the StringBuilder. Finally using insert method "Java " is insert at offset 0.

THINGS TO TRY
  • Try using other inputs for StringBuilder at LINE A.
  • Try using other inputs in append at LINE B.
  • Try using other inputs in insert at LINE C.
  • Try using other methods by referring to the links given above.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.