How to convert StringBuffer to String in Java


Here we will learn how to convert StringBuffer to String using toString method of String class in Java.

Source Code

package com.beginner.examples;

public class StringBufferToString {

	public static void main(String[] args) {
		
		//create StringBuffer.
		StringBuffer stringBuffer = new StringBuffer("Hello World!");
		
		/*
		 * Use toString() method of StringBuffer to convert StringBuffer to String.
		 */
		String string = stringBuffer.toString();
		
		System.out.println("StringBuffer to String: " + string);
	}

}

Output:

StringBuffer to String: Hello World!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Convert StringBuffer to String in Java


In this example we will show how to remove leading and trailing space from string with trim method of String class in Java.

Source Code

package com.beginner.examples;

public class StringBufferToStringUsingTrim {

	public static void main(String[] args) {
		
		//create StringBuffer.
		StringBuffer stringBuffer = new StringBuffer("   Hello World  !  ");
		
		/*
		 *Use trim method of String to convert StringBuffer to String.
		 */
		String string = stringBuffer.toString().trim();
		System.out.println(string );

	}

}

Output:

StringBuffer trim: Hello World  !
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments