Java String toCharArray() Method Example

1. Introduction

The String.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 the toCharArray() 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 using toCharArray().

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:
H
e
l
l
o
,
J
a
v
a
!

Explanation:

1. String str = "Hello, Java!": Declares and initializes a String variable str.

2. char[] charArray = str.toCharArray(): Calls the toCharArray() method on str to convert it into a character array charArray.

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


Comments