Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with StringBuffer and StringBuilder Class in Java

[post-views]

 

In this lesson, you will learn

  • The StringBuffer Class
  • Methods of StringBuffer
  • Examples
  • The StringBuilder Class

 

StringBuffer Class

The StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike String immutable objects StringBuffer objects can be modified after they are created.

 

This makes StringBuffer particularly useful when you need to modify strings of characters.

 

StringBuffer Constructors

StringBuffer defines these four constructors

 

StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)

 

StringBuffer()

Constructs a string buffer with no characters and an initial capacity of 16 characters.

StringBuffer sb = new StringBuffer();

The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.

 

StringBuffer(int capacity)

Constructs a string buffer with no characters and the specified initial capacity.

StringBuffer sb = new StringBuffer(50);

 

StringBuffer(String str)

Constructs a string buffer initialized to the contents of the specified string.

StringBuffer sb = new StringBuffer("Hello");

Sets the initial contents of the StringBuffer object and reserves room for 16 more characters without
reallocation

 

StringBuffer(CharSequence seq)

Constructs a string buffer that contains the same characters as the specified CharSequence.

StringBuffer sb = new StringBuffer("Hello");

Creates an object that contains the character sequence contained in chars and reserves room for 16 more characters.

 

Methods of StringBuffer

 

length( ) and capacity( )

length() returns the length of the character sequence in the buffer, and capacity() returns the current capacity.

 

Syntax

int length( )
int capacity( )

 

Example

StringBuffer sb = new StringBuffer("Hello");
int len = sb.length(); // 5
int cap = sb.capacity(); // 21 (16 default capacity + 5 characters)

 

ensureCapacity()

Ensures that the capacity is at least equal to the specified minimum.

 

Syntax

void ensureCapacity(int minCapacity)

 

Example

StringBuffer sb = new StringBuffer();
sb.ensureCapacity(50);

 

setLength()

Sets the length of the character sequence. If the sequence is shortened, characters are lost; if it is extended, null characters are added.

 

Syntax

StringBuffer sb = new StringBuffer("Hello");
sb.setLength(2);
// sb = "He"

 

charAt(), setCharAt()

The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ).

 

Syntax

char charAt(int where)
void setCharAt(int where, char ch)

 

Example

StringBuffer sb = new StringBuffer("Hello World");
char c = sb.charAt(0); // 'H'
sb.setCharAt(0, 'Y'); // "Yello World"

 

append( )

It appends data of various types to the end of the StringBuffer.

 

Syntax

StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

 

Example

package ch11.l5;

public class StringBufferAppendExample {
    public static void main(String[] args) {
    	// Initialize a StringBuffer with a basic greeting
        StringBuffer sb = new StringBuffer("Greeting: ");

        // Append various data types
        sb.append("Hello, "); // Append a String
        sb.append('A'); // Append a char
        sb.append(true); // Append a boolean
        sb.append(123); // Append an int
        sb.append(45.67); // Append a double
        char[] arr = {' ', 'W', 'o', 'r', 'l', 'd'};
        sb.append(arr); // Append a char array
        
        // Print the final string
        System.out.println(sb);
    }
}

 

Output

Greeting: Hello, Atrue12345.67 World

 

insert( )

Allowing you to insert data of various types into a specific position within the StringBuffer.

Syntax

StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

 

Example

package ch11.l5;

public class StringBufferInsertExample {
    public static void main(String[] args) {
        // Create a StringBuffer object
        StringBuffer sb = new StringBuffer("0123456789");

        // Insert a string at index 4
        sb.insert(4, " inserted string ");
        // Now sb = "0123 inserted string 456789"

        // Insert a character at index 0
        sb.insert(0, 'A');
        // Now sb = "A0123 inserted string 456789"

        // Insert an array of characters at index 10
        char[] charArray = {'C', 'h', 'a', 'r', 's'};
        sb.insert(10, charArray);
        // Now sb = "A0123 inserted Chars string 456789"

        // Insert a boolean value at index 5
        sb.insert(5, true);
        // Now sb = "A0123 true inserted Chars string 456789"

        // Insert an integer at index 24
        sb.insert(24, 1234);
        // Now sb = "A0123 true inserted Chars st1234ring 456789"

        // Insert a float value at index 30
        sb.insert(30, 5.67f);
        // Now sb = "A0123 true inserted Chars st1234ring 5.67456789"

        // Display the final result
        System.out.println(sb.toString());
    }
}

 

Output

A0123true inseCharsrted 1234st5.67ring 456789

 

reverse( )

It used to reverse the characters within the StringBuffer itself.

 

Syntax

StringBuffer reverse( )

 

Example

public class StringBufferReverseExample {
    public static void main(String[] args) {
        // Create a StringBuffer with some text
        StringBuffer sb = new StringBuffer("Hello World");

        // Reverse the StringBuffer contents
        sb.reverse();

        // Display the reversed string
        System.out.println("Reversed string: " + sb.toString());
    }
}

 

Reversed string: dlroW olleH

 

delete( ) and deleteCharAt( )

The delete( ) method deletes a sequence of characters. The substring deleted runs from startIndex to endIndex–1.

 

Syntax

StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)

 

deleteCharAt(int index ): Removes the character at the specified position in this sequence, shifting any subsequent characters to the left.

 

Example

package ch11.l5;

public class StringBufferDeleteExample {
    public static void main(String[] args) {
        // Create a StringBuffer with some text
        StringBuffer sb = new StringBuffer("This is a test string.");

        // Delete a range of characters from index 5 to 10 ("is a")
        sb.delete(5, 10);

        // Display the string after deletion
        System.out.println("After delete: " + sb.toString());
        // Output: "This a test string."

        // Delete the character at index 0 ('T')
        sb.deleteCharAt(0);

        // Display the string after deleting character at index 0
        System.out.println("After deleteCharAt: " + sb.toString());
        // Output: "his a test string."
    }
}

 

Output

StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)

 

replace( )

It is used to replace a sequence of characters in the StringBuffer with another sequence of characters.

 

Syntax

StringBuffer replace(int startIndex, int endIndex, String str)

 

Example

package ch11.l5;

public class StringBufferReplaceExample {
    public static void main(String[] args) {
        // Create a StringBuffer with some text
        StringBuffer sb = new StringBuffer("Hello, Java!");

        // Replace "Java" with "World"
        sb.replace(7, 11, "World");

        // Display the updated string
        System.out.println(sb.toString()); // Output: "Hello, World!"
    }
}

 

Output

StringBuffer replace(int startIndex, int endIndex, String str)

 

substring( )

Syntax

String substring(int startIndex)
String substring(int startIndex, int endIndex)

 

Example

package ch11.l5;

public class StringBufferSubstringExample {
    public static void main(String[] args) {
        // Create a StringBuffer with some text
        StringBuffer sb = new StringBuffer("Hello, World!");

        // Extract substring from index 7 to the end
        String str1 = sb.substring(7);
        System.out.println("Substring from index 7: " + str1); // Output: "World!"

        // Extract substring from index 0 to 5 (exclusive)
        String str2 = sb.substring(0, 5);
        System.out.println("Substring from index 0 to 5: " + str2); // Output: "Hello"
    }
}

 

Output

Substring from index 7: World!
Substring from index 0 to 5: Hello

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review