StringBuilder and StringBuffer help you change text without making new copies every time. This saves memory and makes your program faster.
StringBuilder and StringBuffer in Java
StringBuilder sb = new StringBuilder(); sb.append("Hello"); String result = sb.toString();
StringBuilder is faster but not safe for programs running many parts at once.
StringBuffer is slower but safe for programs running many parts at once.
StringBuilder sb = new StringBuilder(); sb.append("Hi"); sb.append(" there"); System.out.println(sb.toString());
StringBuffer sbf = new StringBuffer("Start"); sbf.append(" and continue"); System.out.println(sbf.toString());
StringBuilder sb = new StringBuilder(); sb.append("Count: "); for(int i=1; i<=3; i++) { sb.append(i).append(", "); } System.out.println(sb.toString());
This program shows how to add text pieces using StringBuilder and StringBuffer, then prints the results.
public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(", "); sb.append("World!"); System.out.println(sb.toString()); StringBuffer sbf = new StringBuffer("Java"); sbf.append(" is fun"); System.out.println(sbf.toString()); } }
Use StringBuilder when you do not need to worry about multiple parts running at the same time.
Use StringBuffer if your program changes text from many parts at once to avoid errors.
Both classes help avoid creating many new strings, which saves memory and time.
StringBuilder and StringBuffer let you build and change text efficiently.
StringBuilder is faster but not thread-safe; StringBuffer is thread-safe but slower.
Use them when you need to change text many times instead of using normal strings.
