Java – How to convert String to StringBuilder and vice-versa ?

In this article, we will discuss how to convert String to StringBuilder and vice-versa

Note: String to StringBuffer conversion is also possible, read StringBuffer to String conversion and vice-versa

String to StringBuilder and vice-versa :

  1. String to StringBuilder using append() method
  2. StringBuilder to String using toString() method

Let us move forward and discuss above conversions

1. String to StringBuilder using append() method of StringBuilder :

Method signature:

public StringBuilder append(String str);

ConvertStringIntoStringBuilderUsingAppendMethod.java

package in.bench.resources.string.to.stringbuilder;

public class ConvertStringIntoStringBuilderUsingAppendMethod {

	public static void main(String[] args) {

		// String - 1
		String str1 = "This is Java Weblog. ";

		// create StringBuilder object
		StringBuilder sb = new StringBuilder();

		// 1. convert String to StringBuilder
		// using append() method
		sb.append(str1);

		// String - 2
		String str2 = "And there are over 500+ articles on Java.";

		// 2. again, convert String-2 to StringBuilder
		// using append() method
		sb.append(str2);

		// String - 3
		String str3 = "Covering most of the Core Java topics.";

		// 3. third time, convert String-3 and
		// add newline '\n' using + operator
		sb.append("\n" + str3);

		// print to console
		System.out.println("Ex: String to StringBuilder"
				+ " using append() method : \n\n" + sb);
	}
}

Output:

Ex: String to StringBuilder using append() method : 

This is Java Weblog. And there are over 500+ articles on Java.
Covering most of the Core Java topics.

2. StringBuilder to String using toString() method of String :

Method signature:

public String toString();

ConvertStringBuilderIntoStringUsingToStringMethod.java

package in.bench.resources.stringbuilder.to.string;

public class ConvertStringBuilderIntoStringUsingToStringMethod {

	public static void main(String[] args) {

		// create StringBuilder object
		StringBuilder sb = new StringBuilder();

		// 1. append some string values
		sb.append("Google is top search-engine. ");

		// 2. again, append some more string values
		sb.append("To get latest topics on Core Java.");

		// 3. third time, append String-3 and
		// add newline '\n'
		sb.append("\nAnd it can search contents in real-time.");

		// convert StringBuilder to String using toString() method
		String str = sb.toString();

		// print to console
		System.out.println("Ex: StringBuilder to String"
				+ " using toString() method: \n\n" + str);
	}
}

Output:

Ex: StringBuilder to String using toString() method: 

Google is top search-engine. To get latest topics on Core Java.
And it can search contents in real-time.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - String v/s StringBuffer
Java - How to convert String to StringBuffer and vice-versa ?