Java String toCharArray() Method Example

1. Introduction

TheString.toCharArray() method in Java converts a string into a new character array. This is useful for situations where you need to manipulate individual characters of a string, such as in sorting algorithms, reverse operations, or custom parsing. This tutorial will demonstrate how to use thetoCharArray() method.

Key Points

-toCharArray() converts the entire string into an array of characters.

- It returns a newly allocated character array.

- The returned array has a length equivalent to the length of the string.

2. Program Steps

1. Declare a string.

2. Convert the string to a character array usingtoCharArray().

3. Print each character of the array.

3. Code Program

public class StringToCharArrayExample {    public static void main(String[] args) {        // String to convert        String str = "Hello, Java!";        // Convert string to character array        char[] charArray = str.toCharArray();        // Print each character from the array        System.out.println("Characters in the array:");        for (char c : charArray) {            System.out.println(c);        }    }}

Output:

Characters in the array:Hello,Java!

Explanation:

1.String str = "Hello, Java!": Declares and initializes aString variablestr.

2.char[] charArray = str.toCharArray(): Calls thetoCharArray() method onstr to convert it into a character arraycharArray.

3. The for loop iterates throughcharArray and prints each character on a new line.


Comments