Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

I'm using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty StringBuilder, but I can't see any method similar to the .NET StringBuilder. Clear in the documentation, just the delete method which seems overly complicated. So what is the best way to clean out a StringBuilder in Java?

1 Answer

0 votes
by (46k points)

setLength method is the best choice as it does not involve any new allocation and garbage collection. The setLength method just resets the internal buffer length variable to 0. The original buffer stays in the memory so new memory allocation is not needed and thus it is the fastest way to clear the StringBuilder. 

 

Syntax:

public void setLength(int newLength)

For clearing the contents of the StringBuilder, we are going to pass 0 as a new length as shown in the below example.

Example:

public class JavaStringBufferClearEmptyExample {

    public static void main(String[] args) {

        

        StringBuilder sbStr = new StringBuilder();

        String strDays[] = {"Sun", "Mon", "Tuesday", "Wed"};

        

        for(int i = 0; i < strDays.length; i++){            

            

            //empty StringBuilder

            sbStr.setLength(0);            

            sbStr.append(strDays[i]); 

            System.out.println(sbStr);

        }

    }

}

Output:

Sun

Mon

Tuesday

Wed

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...