English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to use delete() and setLength() methods to clear the string buffer and create a new StringBuffer object in Java.
class Main { public static void main(String[] args) { //Create a string buffer StringBuffer str = new StringBuffer(); //Add the string to the string buffer str.append("Java"); str.append(" is"); str.append(" popular."); System.out.println("StringBuffer: ", + str); //Clear the string //Using delete() str.delete(0, str.length()); System.out.println("Updated StringBuffer: ", + str); } }
Output Result
StringBuffer: Java is popular. Updated StringBuffer:
In the above example, we used the delete() method of StringBuffer class to clear the string buffer.
Here, the delete() method will delete all characters within the specified index.
class Main { public static void main(String[] args) { //Create a string buffer StringBuffer str = new StringBuffer(); //Add the string to the string buffer str.append("Java"); str.append(" is"); str.append(" awesome."); System.out.println("StringBuffer: ", + str); //Clear the string //Using setLength() str.setLength(0); System.out.println("Updated StringBuffer: ", + str); } }
Output Result
StringBuffer: Java is awesome. Updated StringBuffer
Here, the setLength() method changes the character sequence in StringBuffer to a new character sequence. And, the length of the new character sequence is set to 0.
Therefore, the old character sequence is garbage collected.
NoteSetLength() method completely ignores the existing character sequence in the string buffer. However, the delete() method accesses the character sequence and deletes it. Therefore, setLength() is faster than delete().
class Main { public static void main(String[] args) { //Create a string buffer StringBuffer str = new StringBuffer(); //Add the string to the string buffer str.append("Java"); str.append(" is"); str.append(" awesome."); System.out.println("StringBuffer: ", + str); //Clear the string //Using new //Here, a new object is created and assigned to str str = new StringBuffer(); System.out.println("Updated StringBuffer: ", + str); } }
Output Result
StringBuffer: Java is awesome. Updated StringBuffer:
Here, new StringBuffer() creates a new StringBuffer object and assigns the previous variable to the new object. In this case, the previous object will be there. But it will not be accessible and will be garbage collected.
Because it does not clear the previous string buffer each time, but creates a new string buffer instead. Therefore, it is less efficient in terms of performance.