# How to convert a string to an array in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 10, 2021, updated Oct 29, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-convert-string-to-array

> A short guide to learn about different ways to convert a string into an array using Java.

In an [earlier article](https://attacomsian.com/blog/java-convert-array-to-string), we discussed different ways to convert an array to a string in Java. Today, you'll learn to convert a string into an array that contains subsets of input string split by a delimiter. 

## Convert a string to an array using `String.split()`

The most common way to [split a string into an array in Java](https://attacomsian.com/blog/java-string-split) is the `String.split()` method.

This method returns a string array by splitting the string using the specified delimiter. The separator can be a string or a regular expression.

Here is an example:

```java
// String as a delimiter
String str = "Apple,Orange,Mango,Banana";

String[] fruits = str.split(",");
System.out.println(Arrays.toString(fruits));
// [Apple, Orange, Mango, Banana]

// Regular expression as the delimiter
String str2 = "Java is awesome ?";

String[] tokens = str2.split("\\s");
System.out.println(Arrays.toString(tokens));
// [Java, is, awesome, ?]
```

## Convert a string to an array using `Pattern.split()`

The `Pattern` class defines a [regular expression](https://attacomsian.com/blog/javascript-regular-expressions) for searching and replacing texts.

First, you need to call the `Pattern.compile()` method to create a pattern. It accepts two parameters: a regular expression string and a flag indicating whether the search is case-insensitive or not.  

Next, the `split()` method is used to split the string into an array according to the specified pattern defined in the first step:

```java
String str = "Fox Dog Loin Tiger";
Pattern pattern = Pattern.compile("\\s");

String[] animals = pattern.split(str);
System.out.println(Arrays.toString(animals));
// [Fox, Dog, Loin, Tiger]
```

## Convert a string to an array using Apache Commons Lang

Finally, the last way to convert a string into an array is the [Apache Commons Lang](https://commons.apache.org/proper/commons-lang/) library. The `split()` method of the `StringUtils` class from Commons Lang transforms a string into an array of strings:


```java
String str = "Fox Dog Loin Tiger";

String[] animals = StringUtils.split(str, " ");
System.out.println(Arrays.toString(animals));
// [Fox, Dog, Loin, Tiger]
```
