Home » Core Java » lang » StringBuilder » Java StringBuilder Example

About Katerina Zamani

Katerina Zamani
Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java StringBuilder Example

StringBuilder object seems like a String object but with the characteristics of an array. Every object of this type is like a sequence of characters that can be modified, since StringBuilder class provides us many methods for changing the content and/or the length of the sequence, for initializing the capacity etc. StringBuilder class is mostly used when we want to concatenate many strings continuously and/or treat them like variable-length arrays.

In this example as you can expect, we are going to show how to use basic operations of StringBuilder class.

 

1. Example of StringBuilder

Create a java class named StringBuilderClass and paste the following code.

StringBuilderClass.java:

package com.javacodegeeks.core.stringbuilder;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class StringBuilderClass {
	final static String filename = "C:/JCG/jcgFile.txt";

	public static void main(String[] args) {

		// StringBuilder with 16 empty elements 
		StringBuilder sb = new StringBuilder();
		sb.append("Hello from JCG");
		System.out.println("sb appends a string: "+sb);
		
		// append a character
		char c = '!';
		sb.append(c);
		System.out.println("sb after appending a char: "+sb);
		
		sb.insert(6, "everyone ");
		System.out.println("sb after insert: "+sb);
		
		// StringBulder with a initialized capacity
		StringBuilder sbnew = new StringBuilder(15);
		sbnew.append(123456789);
		System.out.println("sb with length "+ sbnew.length() +" and capacity "+ sbnew.capacity() +
				" appends an int: "+sbnew);
		
		// delete 234
		sbnew.delete(1,4);
		System.out.println("sb after delete: "+sbnew);
		
		// read from a file and append into a StringBuilder every new line
		try {
			BufferedReader br = new BufferedReader(new FileReader(filename));
		
	        StringBuilder sbFile = new StringBuilder();
	        String line = br.readLine();

	        while (line != null) {
	        	// append the line of the file
	        	sbFile.append(line);
	        	// separate the line with a '@'
	        	sbFile.append('@');
	        	
	        	// read the next line of the file
	            line = br.readLine();   
	        }
	        // this string contains the character sequence
	        String readFile = sbFile.toString();
	        br.close();
	        System.out.println("from file: "+readFile);
	       
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		} 
		
	}
}

Now lets explain the code above. Firstly we create an instance of StringBuilder where the default capacity is 16, which means 16 empty characters. In order to add a string, append() method is called with the specified string as a parameter. We can append more data type in the string builder, if we add the specific built-in data types as a parameter in append() method. Also Java provides insert() operation, so we can insert the string representation of a data type in a specific offset of the sequence. As you can notice in the code above, we want to insert the string everyone into the 6th position of the current string builder.

In addition, StringBuilder supports length() method which returns the current number of characters in the string builder sequence, as well as capacity() method which indicates the allocation of character space of the string builder. In this example we create an instance of StringBuilder and we set its capacity to 15. So, after the append of a 9-digit integer, the expecting length is 9 and the capacity is 15. Notice that the capacity cannot be less than 0 but can be greater than or equal to the length of the string builder. Moreover we can remove a specific portion of the string builder, by calling delete() operation. In this situation we should indicate the part of the string builder we want to delete, by setting the start and the end-1 of the removing substring.

In conclusion, we show the advantage that StringBuilder class offers for a better performance. In this situation we read all the lines of a file and append them into a string builder, separated by ‘@’ character, until the end of the file. Finally, we call toString() method in order to take the string representation of the string builder.

After the explanation, you can see the expected results of the execution in the output below.

Output:

sb appends a string: Hello from JCG
sb after appending a char: Hello from JCG!
sb after insert: Hello everyone from JCG!
sb with length 9 and capacity 15 appends an int: 123456789
sb after delete: 156789
from file: Wed Mar 19 13:25:08 EET 2014@Write something in a line. i = 6@A new object@JCG Test@

Download the source file

This was a tutorial about StringBuilder in Java. Download the source code of this example: StringBuilderExample.zip

(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Priya Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Priya
Guest

StringBuilder that is the string object whose value can be changed . It is very important concept in java. Many thanks for sharing.