Convert String to Array in Java

Convert String to Array in java

When developing applications in Java there are many cases where we will find ourselves converting data from one type to the other.

Developers must understand how this is done because it will enhance their system effectiveness leading to ease of use from different users interacting with the system.

How to convert String to Array in Java

In this tutorial, we will learn how to convert String to array in Java and an example use case in an application is when we want to break the input search into several sequences and return results based on a sequence that matches a record from our data source.

A String is a data type that is implemented by a sequence of characters in double-quotes such as "Hello! World" while an array is a data structure that allows us to insert, traverse, delete, and search elements of a particular data type.

Using toArray() method of Set

A Set is a collection that only supports unique elements and it provides us with a method that we can leverage to convert a string to an array.

This method is called toArray() and is a generic method which means it can also be applied to other data types in Java.

To achieve this we will create a new array of size 0 and pass it to this method. The collection of elements in the Set will be added to this array and the method will return an array containing our elements.

Note that if the array created is less than the size of the collection the method creates a new array with the same size as the collection to accommodate all the values and returns the new array.

If the size of the array is large than the size of the collection the remaining storage locations are set to null.

The type of array returned by this method is of the same type as that of the specified array and the method throws an ArrayStoreException if the specified array type is not a supertype of every element in the collection.

The method also throws a NullPointerException if the specified array is null.


[Kangaroos are not dangerous, Kangaroos live in australia]

Using the split() method of String class

The split() method of the Stringg class uses a regular expression to split the string by every string that matches the specified regular expression.

The splitting is done by terminating a string with another substring that matches the given regular expression.

The method returns an array consisting of the terminated substrings and the elements are arranged in the order they appear in the original string.

If the regular expression does not match any substring the resulting array has only one element which is this string.

If the regular expressions syntax cannot be recognized the method throws a PatternSyntaxException.


[Kangaroos, live, in, australia]

Using StringTokenizor class

From the name of the class, we can conclude that this class provides the functionality to break a string into tokens.

Tokens is a term mostly in programming to refer to a single element such as an identifier, keyword, constants, operators, and separators.

Note that the StringTokenizer cannot differentiate between identifiers, numbers, quoted strings, or how to jump comments but uses delimiters to break the string into tokens.

We will use this functionality to convert our string to an array by fetching each token obtained from our string and adding it to a new array.

Since we want to break our string using a whitespace delimiter, we will pass string whitespace in the second parameter of the StringTokenizer.

The size of our array will be managed by the countTokens() method of the StringTokenizer that returns an int value indicating the number of tokens that are remaining in the string.

We will use a while loop that will consume the hasMoreTokens() method checks if there are more tokens in the string and returns true if there is at least one element and false otherwise.

When the condition evaluates to true we use the nextToken() method to get the next element and add it to our new array.

A counter starting from 0 is used to increment the loop and we also use the counter value as the index of the element in our array.

Note that the use of StringTokenizer is discouraged in new code and it is only maintained for compatibility reasons because it is a legacy class.

The split() method which is discussed in this tutorial, should be used as an alternative to achieving similar functionality.


[Kangaroos, live, in, australia]

Using the split() method of StringUtils class

Thie StringUtils class is part of the apache commons library and we have to add it to our application by downloading the library and adding it to our classpath or adding a dependency to our project object model file (pom.xml) if on a Maven environment.

The StringUtils class provides a static method that returns an array of strings by providing two parameters, the first being the original string and the second being the character used to split the string.

We will split our string using the whitespace separators by passing a whitespace string in the second parameter as shown below.


[Kangaroos, live, in, australia]

Using split() method of Pattern class

The split() method of Pattern class works the same way as that of the String class apart from the fact that the regular expression provided must first be compiled to an instance of this class.

For example, if we provide the regular expression \s it will be compiled to \t\n\x0B\f\r and used by the matcher class to match the provided string with the compiled regular expression.

If the match returns true, the string will be split at this point and a new array containing our substrings returned.

Since the compile() and split() are static and the compile method returns a Pattern we can chain the split method to the compile method which helps make our code cleaner.


[Kangaroos, live, in, australia]


In this tutorial, we have learned how to convert a String to an array by implementing five solutions which include using the toArray() method of Set, using StringTokenizor class, using the split() method of StringUtils class, using the split() method of String class, and concluded with using split() method of Pattern class.

That’s all about how to convert String to array in java.

Was this post helpful?

Related Posts

  • 09 January

    Convert Set to String in Python

    Table of ContentsWays to convert set to string in PythonUsing the str() functionUsing the repr() functionUsing the join() functionUsing the map() functionConclusion Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python. Ways to convert set to string in Python […]

  • Convert float to int in Python
    19 June

    Convert float to int in Python

    Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

  • Java BigDecimal to Double
    17 May

    Java BigDecimal to Double

    Learn about how to convert BigDecimal to Double in java

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

  • Convert Date to LocalDate in java
    12 January

    Java Date to LocalDate

    Table of ContentsUsing toInstant() method of Date classUsing toInstant() method of Date classUsing java.sql.Date In this post, we will see how to convert Date to LocalDate in java. Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java. Read […]

  • Convert LocalDate to Date in java
    11 January

    Java LocalDate to Date

    Table of ContentsUsing Instant objectUsing java.sql.Date In this post, we will see how to convert LocalDate to Date. Java 8 has introduced a lot of new APIs for Date and time. There can be many ways to convert Java LocalDateTime to date. Using Instant object You can convert LocalDate to Date using Instant object which […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.