Knowledge Walls
John Peter
Pune, Maharashtra, India
How to handle large string append in java with example
11345 Views
Hints 
Either use StringBuffer or StringWriter for appending large strings in Java.

Wrong
String numberList = "";

for (int i=1;i<=100000;i++){
     //Append multitime to the same string variable each time allocates new memory to take time.
     numberList += i + "\n";
}
StringWriterExample
import java.io.StringWriter;

public class StringWriterExample {
    public static void main(String args[]) throws Exception {
        StringWriter numberList = new StringWriter();

        for (int i=1;i<=100000;i++){
            numberList.write(i + "\n");
        }
        
        System.out.println(numberList);
    }
}
Output 
1
2
3
4
-
-
-
99999
100000
Previous Topics
Previous lessons of current book.
Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details