Java String getChars() Method Example

1. Introduction

The Java String.getChars() method is used to copy characters from a string into a target character array. This method is particularly useful when you need to extract a substring from a string and work with it as an array of characters, rather than as a new String object. This tutorial will demonstrate how to use the getChars() method effectively.

Key Points

- getChars() copies characters from a specified source range within a string to a destination part of a character array.

- The method parameters include the start and end indices in the source string, the destination character array, and the start position in the destination array.

- This method does not return a value; it directly modifies the destination array.

2. Program Steps

1. Declare a source string.

2. Prepare a character array to hold the characters.

3. Specify the source range and the destination start index.

4. Use getChars() to copy the characters.

5. Print the destination array.

3. Code Program

public class StringGetCharsExample {
    public static void main(String[] args) {
        // Source string from which characters will be copied
        String sourceStr = "Hello, Java!";
        // Destination array, which will hold the copied characters
        char[] destArray = new char[10];
        // Start and end indices for the source string
        int srcBegin = 7;
        int srcEnd = 11;
        // Start position in destination array
        int dstBegin = 0;
        // Copy characters into destination array
        sourceStr.getChars(srcBegin, srcEnd, destArray, dstBegin);
        // Output the characters in the destination array
        System.out.println("Copied characters: ");
        for (char c : destArray) {
            System.out.print(c);
        }
    }
}

Output:

Copied characters: Java

Explanation:

1. String sourceStr = "Hello, Java!": Declares and initializes a String variable sourceStr.

2. char[] destArray = new char[10]: Initializes an array destArray to hold characters.

3. Integers srcBegin = 7 and srcEnd = 11: Specify the substring from index 7 to 10 (end index is exclusive) in sourceStr to be copied.

4. int dstBegin = 0: Sets the start index in destArray where the characters will be copied.

5. sourceStr.getChars(srcBegin, srcEnd, destArray, dstBegin): Copies characters from sourceStr to destArray from the specified source indices to the destination starting at dstBegin.

6. The loop prints each character from destArray to display the copied characters.


Comments