How to use the StringBuilder class in Java?

In Java, you can use the StringBuilder class by following these steps:

  1. A tool used for building strings efficiently in Java is called a StringBuilder.
StringBuilder sb = new StringBuilder();
  1. add at the end
sb.append("Hello");
sb.append(" ");
sb.append("World");
  1. Convert to a string
String finalString = sb.toString();
  1. add or place in
  2. remove()
  3. Substitute

Here is a complete sample code:

public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("Hello");
        sb.append(" ");
        sb.append("World");
        
        String finalString = sb.toString();
        System.out.println(finalString); // 输出:Hello World
    }
}

Using the StringBuilder class is an efficient way to handle a large number of string concatenation operations, as it does not create new string objects but instead works on the original string, thereby improving performance.

bannerAds