Introduction
A string is just a series of characters(char). In Java, the String is a Class and not a data type like 'int & char'. Thus, the String class represents String characters, and all string objects in Java are instances of this type. The string class is the most useful in Java programming and Selenium WebDriver. In this blog, we will learn about the String class' getChars() Method in Java with the help of a few examples.
getChars() Method
The java string getChars() function transfers characters from a string into a character array.
Syntax
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Parameters
Here is a list of parameters:
- srcBegin is the index of the first char to copy in the String.
- srcEnd indexes after the final character to be copied in the String.
- dst is the array's destination.
- dstBegin is the offset at which the destination array begins.
Return
It returns no value but throws an IndexOutOfBoundsException.
Must Read: Java System Out Println
Exception Throws
When any of the following conditions is present, the method throws a StringIndexOutOfBoundsException:
- If the value of srcBeginIndex is less than zero.
- If srcBeginIndex exceeds srcEndIndex.
- If srcEndIndex is higher than the length of the string that invokes the function, the method is called.
- If the value of dstEndIndex is less than zero.
- If the sum of dstEndIndex + (srcEndIndex - srcBeginIndex) exceeds the size of the destination array.
Internal Implementation
The syntax for getChars() is:
void getChars(char dst[], int dstBegin) {
// copies value from 0 to dst - 1
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
Must Read Array of Objects in Java
Example-1
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to CodingNinjas Portal");
char[] Str2 = new char[7];
try {
Str1.getChars(2, 9, Str2, 0);
System.out.print("Copied Value = " );
System.out.println(Str2 );
} catch ( Exception ex) {
System.out.println("Raised exception...");
}
}
}
Output
Copied Value = lcome t
Example-2
// exception condition in working of getChars() method
class Coding Ninjas Studio {
public static void main(String args[])
{
String str = "Welcome! to Coding Ninjas Studio";
char[] destArray = new char[20];
try {
// Starting index 0 and ending index 24
str.getChars(12, 26, destArray, 0);
System.out.println(destArray);
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
Output
java.lang.StringIndexOutOfBoundsException: begin 12, end 26, length 22
Must Read: String Args in Java