Hello World

[펌]Java StringBuilder Example 본문

Java/Core

[펌]Java StringBuilder Example

EnterKey 2016. 1. 20. 11:18
반응형

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:

01package com.javacodegeeks.core.stringbuilder;
02 
03import java.io.BufferedReader;
04import java.io.FileNotFoundException;
05import java.io.FileReader;
06import java.io.IOException;
07 
08public class StringBuilderClass {
09    final static String filename = "C:/JCG/jcgFile.txt";
10 
11    public static void main(String[] args) {
12 
13        // StringBuilder with 16 empty elements
14        StringBuilder sb = new StringBuilder();
15        sb.append("Hello from JCG");
16        System.out.println("sb appends a string: "+sb);
17         
18        // append a character
19        char c = '!';
20        sb.append(c);
21        System.out.println("sb after appending a char: "+sb);
22         
23        sb.insert(6"everyone ");
24        System.out.println("sb after insert: "+sb);
25         
26        // StringBulder with a initialized capacity
27        StringBuilder sbnew = new StringBuilder(15);
28        sbnew.append(123456789);
29        System.out.println("sb with length "+ sbnew.length() +" and capacity "+ sbnew.capacity() +
30                " appends an int: "+sbnew);
31         
32        // delete 234
33        sbnew.delete(1,4);
34        System.out.println("sb after delete: "+sbnew);
35         
36        // read from a file and append into a StringBuilder every new line
37        try {
38            BufferedReader br = new BufferedReader(new FileReader(filename));
39         
40            StringBuilder sbFile = new StringBuilder();
41            String line = br.readLine();
42 
43            while (line != null) {
44                // append the line of the file
45                sbFile.append(line);
46                // separate the line with a '@'
47                sbFile.append('@');
48                 
49                // read the next line of the file
50                line = br.readLine();  
51            }
52            // this string contains the character sequence
53            String readFile = sbFile.toString();
54            br.close();
55            System.out.println("from file: "+readFile);
56            
57        catch (FileNotFoundException e) {
58            e.printStackTrace();
59        }catch (IOException e) {
60            e.printStackTrace();
61        }
62         
63    }
64}

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 callingdelete() operation. In this situation we should indicate the part of the string builder we want to delete, by setting thestart 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.z


출처: http://examples.javacodegeeks.com/core-java/lang/stringbuilder/java-stringbuilder-example

반응형
Comments