getChars(): This method is available in java.lang.StringBuffer class of Java.
Syntax:
void java.lang.StringBuffer.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
This method takes four parameters, first and second of type int, third of type char array, and fourth of type int as its parameters. Characters are copied from this sequence into thedestination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1.
Note: 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
Parameter: Four parameters are required for this method.
srcBegin: start copying at this offset.
srcEnd: stop copying at this offset.
dst: the array to copy the data into.
dstBegin: offset into dst.
Throws:
IndexOutOfBoundsException - if any of the following is true:
1. srcBegin is negative.
2. dstBegin is negative.
3. the srcBegin argument is greater than the srcEnd argument.
4. srcEnd is greater than this.length().
5. dstBegin+srcEnd-srcBegin is greater than dst.length
Approach 1: When the index is in the range.
Java
import java.util.Arrays;public class GetChars {public static void main(String[] args) {StringBuffer str = new StringBuffer("Hello World");int srcBegin = 2, srcEnd = 8;char dst[] = { 'a', 'b', 'c', 'l', 'o', 'W' };int dstBegin = 0;str.getChars(srcBegin, srcEnd, dst, dstBegin);System.out.println(Arrays.toString(dst));}}
Output:
[l, l, o, , W, o]
Approach 2: When the index is out of range.
Java
import java.util.Arrays;public class GetChars {public static void main(String[] args) {StringBuffer str = new StringBuffer("Hello World");int srcBegin = -1, srcEnd = 8;char dst[] = { 'a', 'b', 'c', 'l', 'o', 'W' };int dstBegin = 0;str.getChars(srcBegin, srcEnd, dst, dstBegin);System.out.println(Arrays.toString(dst));}}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start -1, end 8, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.getChars(AbstractStringBuilder.java:508) at java.base/java.lang.StringBuffer.getChars(StringBuffer.java:283)
No comments:
Post a Comment