Table of Contents

    StringBuffer getChars() Method in Java: Usage and Examples

    Sometimes, it may be needed to copy a few characters of string content of StringBuffer to an array or to copy the complete StringBuffer into an array. Here, getChars() method comes into usage.

    Syntax

    void getChars(int sourceStart, int sourceEnd, char target[ ],int targetStart)

    Parameters

    sourceStart specifies the index of the beginning of the substring

    sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd-1.The array that will receive the characters is specified by target.

    The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.

    sourceStart - start copying at this offset. sourceEnd - stop copying at this offset. target - the array to copy the data into. targetStart - offset into target.

    Throws

    NullPointerException - if dst is null. IndexOutOfBoundsException - if any of the following is true:

    • sourceStart is negative
    • targetStart is negative
    • the sourceStart argument is greater than the sourceEnd argument.
    • sourceEnd is greater than this.length().
    • targetStart+sourceEnd-sourceStart is greater than target.length

     

    Returns

    Program

    public class StringGetCharsExample{
    public static void main(String args[]){
     String str = new String("hello I think I am fool");
          char[] ch = new char[10];
          try{
             str.getChars(6, 16, ch, 0);
             System.out.println(ch);
          }catch(Exception ex){System.out.println(ex);}
      }
     }

    Output

    I think I
    Press any key to continue . . .

    Program

    public class DemogetChars
    {
      public static void main(String args[])
      {
       StringBuffer sb1 = new StringBuffer("ABCDEFGHI");
       char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    
       System.out.println("Array before copying: "  + new String(ch));  // 0123456789
    
       sb1.getChars(1, 4, ch, 4);
    
       System.out.println("Array after copying: "  + new String(ch));  // 0123BCD789
      }
    }

    Output

    Array before copying: 0123456789
    Array after copying: 0123BCD789
    Press any key to continue . . .