
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Buffer Strings in Java
Buffering strings is a technique where the system temporarily stores parts of the strings in a buffer before processing them or printing them out. The following are different methods in Java to buffer a string
Using the emit method for string buffering
Using the StringBuffer class
Using the emit method for string buffering
The emit method collects parts of a string into a buffer and returns the buffer once it reaches a certain length. This reduces the inefficiency caused by continuous string concatenations.
Example
The following is an example using the emit method for string buffering
public class StringBuffer { public static void main(String[] args) { countTo_N_Improved(); } private final static int MAX_LENGTH = 30; private static String buffer = ""; private static void emit(String nextChunk) { if(buffer.length() + nextChunk.length() > MAX_LENGTH) { System.out.println(buffer); buffer = ""; } buffer += nextChunk; } private static final int N = 100; private static void countTo_N_Improved() { for (int count = 2; countOutput
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82Using the StringBuffer Class
StringBuffer is a class that represents a mutable sequence of characters. It offers an alternative to the immutable String class and enables you to change the contents of a string without having to create a new object every time.
Example
The following is an example using the StringBuffer class
public class HelloWorld { public static void main(String []args) { StringBuffer sb = new StringBuffer("hello"); sb.append("world"); sb.insert(0, " Tutorialspoint"); System.out.print(sb); } }Output
Tutorialspointhelloworldjava_strings.htm