Menu
Topics Index
...
`


Strings > StringBuffer >
Siva Nookala - 05 Apr 2016
The getChars method copies the characters in a sequence into the destination character array dst.

StringBuffer Method:
MethodDescription
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Characters are copied from this sequence into the destination character array dst.

  • The first character to be copied is at index srcBegin.
  • The last character to be copied is at index srcEnd - 1.
  • The total number of characters to be copied is srcEnd - srcBegin.
  • The characters are copied into the subarray of dst starting at index dstBegin and ending at index: dstbegin + (srcEnd-srcBegin) - 1.

StringBufferDemo3
class StringBufferDemo3
{
    public static void main(String[] args) {
    
        StringBuffer buff = new StringBuffer("Java Programming"); // LINE A
        System.out.println("Buffer = " + buff);
    
        // char array
        char[] array = new char[]{'M','e','r','i','t',' ','C','a','m','p','u','s'}; // LINE B
    
        // copy the chars from index 5 to index 12 into subarray of array
        // the offset into destination subarray is set to 5
        buff.getChars(5, 12, array, 5); // LINE C
        // print character array
        System.out.println(array);
    }
}
OUTPUT

Buffer = Java Programming
MeritProgram

DESCRIPTION

First, "Java Programming" is taken into the StringBuffer in LINE A. Then 'M','e','r','i','t',' ','C','a','m','p','u','s' is taken into the char[] in LINE B. In LINE C the characters are copied into the char[] from index 5 to index 12 of the StringBuffer containing "Java Programming" starting at index 5 of the char[].

THINGS TO TRY
  • Try using inputs other than "Java Programming" in the StringBuffer in LINE A.
  • Try using inputs other than 'M','e','r','i','t',' ','C','a','m','p','u','s' in the char[] in LINE B.
  • Place the below code at LINE C and see the output. It should throw ArrayIndexOutOfBoundsException, since given value 12 (dstBegin value) exceeded the length of the array.
    buff.getChars(5, 12, array, 12);

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.