setLength(int newLength)方法用于更改StringBuffer对象的长度。它设置字符序列的长度。字符序列更新为新的字符序列,其长度由方法中作为参数传递的值确定。newLength应该大于或等于零。
声明java.lang.StringBuffer(int newLength)方法如下-
public void setLength(int newLength)
让我们看一个示例程序,该示例说明setLength(int newLength)方法的用法
public class Example {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
System.out.println(sb);
System.out.println("Original length : "+sb.length());
System.out.println("Original capacity : "+sb.capacity());
sb.setLength(5); // changing the length of the StringBuffer object
System.out.println();
System.out.println(sb);
System.out.println("New length : " +sb.length());
System.out.println("New capacity : " +sb.capacity());
}
}输出结果
Hello World Original length : 11 Original capacity : 27 Hello New length : 5 New capacity : 27