Java StringBuffer With Method Examples

StringBuffer in Java is a thread-safe, mutable sequence of characters thus using StringBuffer class you can create modifiable String objects.

In the post String in Java we have already seen that String objects are immutable i.e. Strings are constant; their values cannot be changed after they are created. Because of this immutability property when you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation. That may lead to creation of lots of intermediate String objects if String is modified several times which in turn means more memory being used for these intermediate objects.

Using StringBuffer object you can avoid this problem of creating several objects as it is mutable. Unsurprisingly the principal operations on a StringBuffer are the append and insert methods.

Important points about Java StringBuffer

Some of the important points about StringBuffer class.

  1. StringBuffer in Java provides much of the functionality of String class with one prominent deviation that StringBuffer is mutable.
  2. StringBuffer is also thread-safe thus StringBuffer object can be safely used by multiple threads. The methods of the StringBuffer class are synchronized where necessary.
  3. Every StringBuffer is created with a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.
  4. Java 5 onward StringBuilder class is also provided which is equivalent to StringBuffer class but designed for use by a single thread. StringBuilder is faster, as it performs no synchronization.

Java StringBuffer Constructors

There are four constructors in StringBuffer class.

  1. StringBuffer()– Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
    StringBuffer sb = new StringBuffer();
    
  2. StringBuffer(int capacity)– Constructs a string buffer with no characters in it and the specified initial capacity.
    StringBuffer sb = new StringBuffer(30);
  3. StringBuffer(CharSequence seq)– Constructs a string buffer that contains the same characters as the specified CharSequence.
    Here CharSequence is an interface which is implemented by CharBuffer, Segment, String, StringBuffer, StringBuilder.
  4. StringBuffer(String str)– Constructs a string buffer initialized to the contents of the specified string.
    StringBuffer sb = new StringBuffer("Hello");

Java StringBuffer method examples

append method

append method is overloaded so as to accept data of any type. This method appends the string representation of the given data type to existing buffer. The append method always adds these characters at the end of the buffer.

public class StringLiteral {
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Hello");
    sb.append(" ");
    sb.append("World").append(" ").append(123);
    System.out.println("Appended String- " + sb.toString());
  }
}

Output

Appended String- Hello World 123

As you can see from the example append is used with String as argument and also int as argument as it is overloaded for these data types. You can also chain append method as done in this code line-

sb.append("World").append(" ").append(123)

Using append method we can also check the statement that the String is immutable where as StringBuffer is mutable. In the example a StringBuffer object is created and then values are appended to it and the returned reference is stored in another StringBuffer.

Same way a String is created and values appended to it, returned String is also referenced by another String.

On checking the equality of two StringBuffer references you can see that both are same whereas for String both are different.

public class StringLiteral  {
	public static void main(String[] args) {
		// With StringBuffer
		System.out.println("StringBuffer...");
		StringBuffer sb = new StringBuffer("Hello");
		sb.append(" ");
		StringBuffer newsb = sb.append("World").append(" ").append(123);
		if (sb == newsb) {
			System.out.println("Reference is same");
		}else {
			System.out.println("Reference is different");
		}
		// With String
		System.out.println("String...");
		String str = "Hello";
		String newstr = str.concat(" ").concat("World").concat(" ").concat("123");
		if (str == newstr) {
			System.out.println("Reference is same");
		}else {
			System.out.println("Reference is different");
		}		
	}
}

Output

StringBuffer...
Reference is same
String...
Reference is different

insert method

insert method is overloaded so as to accept data of any type. This method is used to insert the string representation of the given data type to existing buffer. The insert method adds the characters at a specified point.

insert method takes two arguments first an integer indicating the position where characters are to be inserted in the buffer and second argument is the text to be inserted.

public class StringLiteral {
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Knp");
    sb.insert(3, "Code");
    System.out.println("String after insert- " + sb);
  }
}

Output

String after insert- KnpCode

length and capacity methods

capacity()– Returns the current capacity of the StringBuffer.

length()– Returns the number of characters in this sequence.

public class StringLiteral  {
  public static void main(String[] args) {		
    StringBuffer sb = new StringBuffer(30);
    sb.append("Hello");
    System.out.println("Capacity of StringBuffer- " + sb.capacity());
    System.out.println("Length of StringBuffer- " + sb.length());
  }
}

Output

Capacity of StringBuffer- 30
Length of StringBuffer- 5

As you can see StringBuffer is created with the capacity as 30 so the capacity is displayed as 30 where as number of characters in the buffer is 5 so the length is displayed as 5.

delete and deleteCharAt methods

  • delete(int start, int end)– Removes the characters in a substring of this sequence. start which indicates the beginning index is inclusive where as end which indicates the ending index is exclusive.
  • deleteCharAt(int index)– Removes the char at the specified position in this sequence.
public class StringLiteral  {
  public static void main(String[] args) {	
    StringBuffer sb = new StringBuffer("Hello");
    sb.delete(1, 4);
    System.out.println("After deletion- " + sb);
    System.out.println("Length of StringBuffer- " + sb.length());
  }
}

Output

After deletion- Ho
Length of StringBuffer- 2
public class StringLiteral  {
	public static void main(String[] args) {	
		StringBuffer sb = new StringBuffer("Hello");
		sb.deleteCharAt(4);
		System.out.println("After deletion- " + sb);
		System.out.println("Length of StringBuffer- " + sb.length());
	}
}

Output

After deletion- Hell
Length of StringBuffer- 4

Java StringBuffer reverse method

reverse()– Reverses the existing StringBuffer.

public class StringLiteral  {
	public static void main(String[] args) {	
		StringBuffer sb = new StringBuffer("Hello");
		System.out.println("Reversed- " + sb.reverse());
	}
}

Output

Reversed- olleH

Java StringBuffer replace method

replace(int start, int end, String str)– Replaces the characters in a substring of this sequence (start to end-1) with characters in the specified String.

public class StringLiteral  {
	public static void main(String[] args) {	
		StringBuffer sb = new StringBuffer("Hello");
		sb.replace(3, 5, "ena");
		System.out.println("String- " + sb);
	}
}

Output

String- Helena

Related Posts

That’s all for the topic Java StringBuffer With Method Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.