setLength

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);
    System.out.println("buffer after = " + sb);
    System.out.println("charAt(1) after = " + sb.charAt(1));
  }
}

The output:


buffer before = java2s.com
charAt(1) before = a
buffer after = ji
charAt(1) after = i

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.

Home 
  Java Book 
    Essential Classes  

StringBuffer:
  1. Create StringBuffer object
  2. append
  3. StringBuffer capacity()
  4. charAt(int index): get the char at specified index
  5. delete(int start, int end) and deleteCharAt(int index)
  6. ensureCapacity( )
  7. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  8. indexOf(String str)
  9. lastIndexOf(String str)
  10. StringBuffer length()
  11. Insert(): add data in the middle of a StringBuffer
  12. replace():replace a StringBuffer
  13. StringBuffer reverse()
  14. setCharAt(int index, char ch)
  15. setLength
  16. substring
  17. toString():Convert StringBuffer to String