Skip to Content

Java StringBuffer setLength Example

  1. /*
  2.         Java StringBuffer setLength Example
  3.         This example shows how to set length of StringBuffer using setLength method
  4.         of StringBuffer class in Java.
  5. */
  6.  
  7. public class JavaStringBufferSetLengthExample {
  8.        
  9.         public static void main(String[] args) {
  10.                
  11.                 //create StringBuffer object
  12.                 StringBuffer sbf = new StringBuffer("StringBuffer setLength method example");
  13.                
  14.                 /*
  15.                  * To set length of StringBuffer, use
  16.                  * void setLength(int newLength) method of
  17.                  * StringBuffer class.
  18.                  *
  19.                  * If newLegth is less than the original length, contents of
  20.                  * StringBuffer would be truncated.
  21.                  *
  22.                  * If newLength is grater than the original length, StringBuffer
  23.                  * would be filled with null characters ('\u0000').
  24.                  */
  25.                
  26.                 sbf.setLength(12);
  27.                 System.out.println("StringBuffer contents: " + sbf);
  28.  
  29.                 /*
  30.                  * To delete or clear contents of StringBuffer,
  31.                  * set length of StringBuffer to 0.
  32.                  */
  33.                
  34.                 sbf.setLength(0);
  35.                 System.out.println("StringBuffer contents deleted:" + sbf);
  36.                
  37.                
  38.         }
  39. }
  40.  
  41. /*
  42. Output of Java StringBuffer setLength example would be
  43. StringBuffer contents: StringBuffer
  44. StringBuffer contents deleted:
  45. */