Java String getChars() Method Tutorial

In this section, we will learn what the String getChars() method is and how to use it in Java.

What is Java String getChars() Method?

The `getChars()` method is used to copy the characters of a string into a char array.

Basically, using this method, we can get the characters of a string value in an array of characters.

Java getChars() Method Syntax:

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

getChars() Method Parameters:

  • `srcBegin`: the first argument of this method is the index number of the source string from which we want to start copying the characters into the target array.
  • `srcEnd`: the second argument is the excluding index number in which we want the copying characters to stop at that index.
  • `dst`: the third argument is the address of the target array in which the characters should be stored in.
  • `dstBegin`: this last argument is the index number of the target array in which we want the characters to be stored from that index forward.

getChars() Method Return Value:

This method does not return a value.

Example: using String getChars() method

public class Simple {

    public static void main(String[] args)  {
        String s1 = "BE KING TO ONE ANOTHER";

        char[] chars = new char[s1.length()];

        s1.getChars(0,s1.length(),chars, 0);

        for(char c: chars){
            System.out.print(c+", ");
        }
    }
}

Output:

B, E, , K, I, N, G, , T, O, , O, N, E, , A, N, O, T, H, E, R,

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies