Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
method
char
array

What is the toCharArray() method in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The char[] (a character array) and String are very similar as they both store a sequence of characters. Although the String class is more extensive (has a ton of functions for manipulating sequence), it is sometimes necessary to convert a String into a character array.

For example, if a function accepts a parameter as char[], we cannot pass a String to it; so, instead of declaring a char[] of size equal to the string’s length and copying every character one by one into it, we can use toCharArray() makes the task easier.


Return value

This function is present in the String class; it returns a char[] populated with the character sequence of the string. The size of this array is equal to the string’s length.

svg viewer

Example

class Main{
public static void main(String[] args){
String str = "Hello world!";
char[] arr = str.toCharArray();
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i]);
System.out.println("\nSize of char[] = " + arr.length);
}
}

RELATED TAGS

java
method
char
array
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring