StringBuffer length and capacity
In this chapter you will learn:
- What is difference between length and capacity of a Java StringBuffer
- How to Pre-allocate space
- How to shorten a StringBuffer
StringBuffer's capacity vs length
The current length of a StringBuffer
can be found via the length( )
method.
The total allocated capacity can be found through the capacity( )
method.
int capacity()
Returns the current capacity.int length()
Returns the length (character count).
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer();
sb.append("java2s.com");
/*from j a v a2s .c o m*/
System.out.println(sb.length());
System.out.println(sb.capacity());
}
}
The output:
The following code trims the unused spaces and checks the length and capacity again.
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer();
sb.append("java2s.com");
// j a va2 s . c o m
System.out.println(sb.length());
System.out.println(sb.capacity());
sb.trimToSize();
System.out.println(sb.length());
System.out.println(sb.capacity());
}
}
The output:
Pre-allocate space with ensureCapacity( )
To preallocate room for a certain number of characters after a
StringBuffer
has been constructed, use
ensureCapacity( )
to set the size of the buffer.
ensureCapacity( )
has this general form:
void ensureCapacity(int capacity)
capacity
specifies the size of the buffer.
public class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer();
sb.ensureCapacity(100 ); //from ja v a 2 s. c o m
sb.append("java2s.com");
System.out.println(sb.capacity());
System.out.println(sb.length());
System.out.println(sb.toString());
}
}
Output:
shorten a StringBuffer
void setLength(int newLength)
Sets the length of the character sequence.
The program in the following section uses setLength()
to shorten a StringBuffer
.
public class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("java2s.com");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);//from j a v a 2s . com
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
The output:
When you increase the size of the buffer, null characters are added to the end of the existing buffer.
If you call setLength( )
with a value
less than the current value returned by length( )
,
then the characters stored beyond the new length will be lost.
Next chapter...
What you will learn in the next chapter:
- How to get a char from a certain index inside a StringBuffer
- How copy part of a StringBuffer to a char array
- How to update a char in a StringBuffer