How to Set Length of StringBuffer in Java


The example aims to set length of StringBuffer using setLength method of StringBuffer class in Java.

Source Code

package com.beginner.examples;

public class JavaStringBufferSetLength {

	public static void main(String[] args) {
		
		//create StringBuffer.
		StringBuffer stringBuffer = new StringBuffer("Hello World");
		
		/*
		 * To set length of StringBuffer, use
		 * void setLength(int newLength) method of StringBuffer.
		 */
		stringBuffer.setLength(5);
		System.out.println("StringBuffer contents: " + stringBuffer);
		
		/*
		 * To delete or clear contents of StringBuffer, 
		 * set length of StringBuffer to 0.
		 */
		stringBuffer.setLength(0);
		System.out.println("StringBuffer contents:" + stringBuffer);
	}

}

Output:

StringBuffer contents: Hello
StringBuffer contents:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments