How to Convert String to Array in Java

Introduction

Sometimes, when working with Java programs, we need to split a String into an array efficiently. This is typically done based on specific delimiters, such as commas, spaces, or even more complex patterns defined by regular expressions. For example, consider reading a line from a CSV file and parsing it to extract all the data into a String array for further processing or storage. This technique is essential for handling structured data, such as user inputs, configuration files, or other types of file contents effectively. In this tutorial, we will explore the different methods to efficiently convert a String into an array in a Java program, providing clear examples and explanations to guide you step by step.

Convert String to Array in Java

The String class’s split(String regex) method can be used to convert a String to an array in Java. If you are working with Java regular expressions, you can also use the Pattern class’s split(String regex) method. Let’s see how to convert a String with a simple Java class example.

Example Code

package com.journaldev.util;

import java.util.Arrays;
import java.util.regex.Pattern;

public class StringToArrayExample {

    /**
     * This class shows how to convert String to String Array in Java
     * @param args
     */
    public static void main(String[] args) {
        String line = "My name is Pankaj";
        //using String split function
        String[] words = line.split(" ");
        System.out.println(Arrays.toString(words));
        //using java.util.regex Pattern
        Pattern pattern = Pattern.compile(" ");
        words = pattern.split(line);
        System.out.println(Arrays.toString(words));
    }
}

Output

[My, name, is, Pankaj]
[My, name, is, Pankaj]

The above program splits the String into an array of words using two different methods: the split method of the String class and the split method of the Pattern class.

Additional Information to Convert String to Array

Java also offers a legacy class called StringTokenizer, but it is outdated and not recommended. This class does not support regular expressions, which makes it less flexible for modern use cases. Additionally, its usage can be confusing and harder to understand for beginners in Java programming. Instead, you should use the split methods provided by the String or Pattern classes. These methods are more versatile and allow splitting Strings into arrays effectively. For advanced cases, Java regular expressions provide powerful tools for handling complex splitting scenarios. Learn more about regular expressions to expand your Java String manipulation skills.