Copy characters from string into char Array in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say we have the following string.

String str = "Demo Text!";

To copy some part of the above string, use the getChars() method.

// copy characters from string into chArray
=str.getChars( 0, 5, chArray, 0 );

The following is an example to copy characters from string into char Array in Java.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Demo Text!";
      char chArray[] = new char[ 5 ];
      System.out.println("String: "+str);
      // copy characters from string into chArray
      str.getChars( 0, 5, chArray, 0 );
      System.out.print("Resultant character array...\n");
      for (char ch : chArray)
         System.out.print( ch );
   }
}

Output

String: Demo Text!
Resultant character array...
Demo
raja
Published on 13-Dec-2018 15:21:08
Advertisements