StringBuilder length and capacity
In this chapter you will learn:
Get the length
int length()
returns the length (character count).
public class Main {
public static void main(String[] argv) {
StringBuilder sb = new StringBuilder();
sb.append("java2s.com");
//from ja v a2s . c om
System.out.println(sb.length());
System.out.println(sb.capacity());
sb.trimToSize();
System.out.println(sb.length());
System.out.println(sb.capacity());
}
}
The output:
Get the capacity
int capacity()
returns the current capacity.
public class Main {
public static void main(String[] a) {
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder(0);
StringBuilder builder3 = new StringBuilder(100);
/*from ja v a2 s. c om*/
System.out.println(builder1.capacity());
System.out.println(builder2.capacity());
System.out.println(builder3.capacity());
}
}
Output:
Next chapter...
What you will learn in the next chapter:
- How to get a single char from StringBuilder
- How to change a single char for StringBuilder
- How to delete a char at specified index
Home » Java Tutorial » String