CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Dates

Dates and Strings
StringBuilder class
Constructors

The StringBuilder and StringBuffer classes is an alternative to the String class. In general, a StringBuilder/StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.

The StringBuilder class

java.lang.StringBuilder

Description

  • StringBuilder objects are mutable, which means you can modify the characters in the string.
  • The capacity of a StringBuilder object is automatically increased if necessary.
  • The StringBuilder class is new for Java 5.0. It's designed to replace the older StringBuffer class, which has identical constructors and methods but isn't as efficient.

Constructors of the StringBuilder class

Constructor Description
StringBuilder() Creates an empty StringBuilder object with an initial capacity of 16 characters.
StringBuilder(intLength) Creates an empty StringBuilder object with an initial capacity of the specified number of characters.
StringBuilder(String) Creates a StringBuilder object that contains the specified string plus an additional capacity of 16 characters

Methods of the StringBuilder class

Method Description
capacity() Returns an int value for the capacity of this StringBuilder object.
length() Returns an int value for the number of characters in this StringBuilder object.
setLength(intNumOfChars) Sets the length of this StringBuilder object to the specified number of characters.
append(value) Adds the value to the end of the string.
insert(index, value) Inserts the value at the specified index, pushing the rest of the string back.
replace(startIndex, endIndex, String) Replaces the characters from the start index to, but not including, the end index with the specified string.
delete(startIndex, endIndex) Removes the substring from the start index to, but not including, the end index.
deleteCharAt(index) Removes the character at the specified index.
setCharAt(index, character) Replaces the character at the specified index with the specified character.
charAt(index) Returns a char value for the character at the specified index.
substring(index) Returns a String object that contains the characters starting at the specified index to the end of the string.
substring(startIndex, endIndex) Returns a String object that contains the characters from the start index to, but not including, the end index.
toString() Returns a String object that contains the string that's stored in the StringBuilder object.

Note

  • The append and insert methods accept primitive types, objects, and arrays of characters.
Previous | Constructors | Code