How to Replace Contents of StringBuffer in Java


This example aims to show how to replace contents of StringBuffer in Java.

Source Code

package com.beginner.examples;

public class StringBufferReplace {

	public static void main(String[] args) {
		
		//Create StringBuffe.
		StringBuffer stringBuffer = new StringBuffer("Alice is smiling");
		
		System.out.println("Before replacement , StringBuffer si : " + stringBuffer);
		
		/*
		 * To replace the contents of Java StringBuffer use replace(int start, int end, String str) method.
		 */
		stringBuffer.replace(0,5,"Bob");
		
		System.out.println("After replacement , StringBuffer si : " + stringBuffer);

	}

}

Output:

Before replacement , StringBuffer si : Alice is smiling
After replacement , StringBuffer si : Bob is smiling
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments