Java string to char array – How to Convert a String to char array in Java? | Java String toCharArray() Method with Example

Java string to char array: In our previous java string tutorials, we have learned how to convert a string to lowercase & Uppercase in java. But today, in this tutorial, we will learn how to convert a string to a char array in Java. To make it possible, we will use the Java String toCharArray() method. So, check the process and signature of the toCharArray() method of the java string class with an example from the below links.

This Tutorial of How to Convert a String to char array in Java includes the following:

Convert a String to Character array in Java

Java string to chararray: We can convert a string to a char array by using the two ways. The following are the two approaches to convert a string to a character array in java:

  • using Java String toCharArray()
  • Naive Approach

Method 1: Java String toCharArray()

Java convert string to char: The java stringtoCharArray()method converts this string into a character array. It returns a newly allocated character array whose length is the length of this string.

Syntax

Tochararray in java: The syntax of the Java String toCharArray() method is given below:

public char[] toCharArray()

It converts this string to a new character array.

Also Check:

Java program to convert a string to char array – Example

class toCharArray{
public static void main(String args[]){
String str = "Java";

//converting string to char array.
char ch[] = str.toCharArray();

//printing the char array.
for(int i=0; i<ch.length; i++){
System.out.println(ch[i]);
}
}
}

Output:

How to Convert a String to char array in Java

Method 2: Naive Approach

Java char array: The following steps are the best way to do the process of converting a string to char array in java using a naive approach:

  1. Get the string.
  2. Create a character array of the same length as of string.
  3. Traverse over the string to copy character at the i’th index of string to i’th index in the array.
  4. Return or perform the operation on the character array.

Let’s see the below-illustrated example to convert a string to a character array in java,

Example on Using Naive Approach to convert string to char array in java

// Java program to Convert a String
// to a Character array using Naive Approach

import java.util.*;

public class BG {

public static void main(String args[])
{
String str = "BtechGeeks";

// Creating array of string length
char[] ch = new char[str.length()];

// Copy character by character into array
for (int i = 0; i < str.length(); i++) {
ch[i] = str.charAt(i);
}

// Printing content of array
for (char c : ch) {
System.out.println(c);
}
}
}

Output: 

B
t
e
c
h
G
e
e
k
s