Last Updated : 17 Nov, 2022
The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method of StringBuffer class copies the characters starting at the index:srcBegin to index:srcEnd-1 from actual sequence into an array of char passed as parameter to function.
Syntax:
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Parameters: This method takes four parameters:
Returns: This method returns nothing. Exception: This method throws StringIndexOutOfBoundsException if:
Below programs demonstrate the getChars() method of StringBuffer Class: Example 1:
Java
// Java program to demonstrate
// the getChars() Method.
import java.util.*;
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer
str
= new StringBuffer("Geeks For Geeks");
// print string
System.out.println("String = "
+ str.toString());
// create a char Array
char[] array = new char[15];
// initialize all character to .(dot).
Arrays.fill(array, '.');
// get char from index 0 to 9
// and store in array start index 3
str.getChars(0, 9, array, 1);
// print char array after operation
System.out.print("char array contains : ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
Output:
String = Geeks For Geeks char array contains : . G e e k s F o r . . . . .
Example 2: To demonstrate StringIndexOutOfBoundsException.
Java
// Java program to demonstrate
// exception thrown by the getChars() Method.
import java.util.*;
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer
str
= new StringBuffer("Contribute Geeks");
// create a char Array
char[] array = new char[10];
// initialize all character to $(dollar sign).
Arrays.fill(array, '$');
try {
// if start is greater then end
str.getChars(2, 1, array, 0);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Output:
Exception: java.lang.StringIndexOutOfBoundsException: srcBegin > srcEnd
References: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#getChars(int, int, char%5B%5D, int)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4