stringbuffercaplen.java

来自「金旭亮的java教案」· Java 代码 · 共 36 行

JAVA
36
字号
// StringBufferCapLen.java
// This program demonstrates the length and
// capacity methods of the StringBuffer class.
import javax.swing.*;

public class StringBufferCapLen {
   public static void main( String args[] )
   {
      StringBuffer buf =
         new StringBuffer( "Hello, how are you?" );

      //length:当前字符个数
      //capacity:不另外分配内存可以存放的字符个数
      
      String output = "buf = " + buf.toString() +
                      "\nlength = " + buf.length() +
                      "\ncapacity = " + buf.capacity();
                      
	  //ensureCapacity:保证StringBuffer的最小容量
      buf.ensureCapacity( 75 );
      output += "\n\nNew capacity = " + buf.capacity();
	  
	  //setLength:增大或减小StringBuffer的长度
      buf.setLength( 10 );
      output += "\n\nNew length = " + buf.length() +
                "\nbuf = " + buf.toString();

      JOptionPane.showMessageDialog( null, output,
         "StringBuffer length and capacity Methods",
         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?