To start you off on your assignment, String.split splits strings on a regular expression and this expression may be an empty string:

String[] ary = "abc".split("");

Yields the array:

(java.lang.String[]) [, a, b, c]

Getting rid of the empty 1st entry is left as an exercise for the reader :-)

Note: In Java 8, the empty first element is no longer included.

Answer from rsp on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_howto_string_to_array.asp
Java How To Convert a String to an Array
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... There are many ways to convert a string to an array.
🌐
freeCodeCamp
freecodecamp.org › news › string-to-array-in-java-how-to-convert-a-string-to-an-array-in-java
String to Array in Java – How to Convert Strings to Arrays
July 6, 2023 - Simplicity: The toCharArray() method provides a straightforward way to convert a string to a character array with just a single method call. Readability: The resulting character array can be easily manipulated, processed, or iterated over using ...
Discussions

string to string array conversion in java - Stack Overflow
I have a string = "name"; I want to convert into a string array. How do I do it? Is there any java built in function? Manually I can do it but I'm searching for a java built in function. I want an... More on stackoverflow.com
🌐 stackoverflow.com
java - Converting String Array to an Integer Array - Stack Overflow
so basically user enters a sequence from an scanner input. 12, 3, 4, etc. It can be of any length long and it has to be integers. I want to convert the string input to an integer array. so int[0] w... More on stackoverflow.com
🌐 stackoverflow.com
How to turn string into array
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
12
1
May 4, 2021
java - Convert String array to string back to string array - Stack Overflow
Here's a sample of the string. It is separated by a comma. ... Update: I've been advised not to use toString to serialize array. But since I'm dealing with simple array, I still opted to use it. ... @Pshemo im new to java so all I know is that I can only save a string, int and boolean to session. More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is a string in Java?
A string in Java is a sequence of characters enclosed within double quotes. String in Java are immutable that means once they are created their value can’t change. Any modifications to a string results in a new string object being created. A string in Java is a sequence of characters enclosed within double quotes. String in Java are immutable that means once they are created their value can’t change. Any modifications to a string results in a new string object being created. In Java, strings are fundamental data types used extensively in software development. However, there are scenarios where
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string to array in java
Converting String to Array in Java: A Comprehensive Guide
Can we convert a string into a list instead of an array?
Yes, a string can be converted into a list by iterating over its characters or using built-in methods that transform it into a list of substrings or characters.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string to array in java
Converting String to Array in Java: A Comprehensive Guide
How to handle empty strings when converting to an array?
You can handle empty strings by checking if the string is empty before conversion, setting a default value, or filtering out empty elements after conversion.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string to array in java
Converting String to Array in Java: A Comprehensive Guide
🌐
Scaler
scaler.com › home › topics › convert string to array in java
String to Array in Java - Scaler Topics
April 19, 2024 - Strings in Java are objects which represent a sequence of characters. Java Strings are immutable, which implies their value cannot be changed once they are created. We can use a simple for loop or toCharArray() method to convert string to char array.
🌐
DigitalOcean
digitalocean.com › community › tutorials › string-to-array-java
How to Convert String to Array in Java | DigitalOcean
August 4, 2022 - From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.
🌐
Hostman
hostman.com › tutorials › converting-arrays-and-strings-in-java
Java Array to String and String to Array Conversion Guide
In Java, strings are treated as objects, and the language furnishes a robust set of methods for the manipulation of textual information. This tutorial provides a comprehensive guide on how to convert arrays to strings and strings to arrays in Java.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › string to array in java
Converting String to Array in Java: A Comprehensive Guide
August 27, 2025 - An array in Java is a data structure that stores multiple values of the same type in a contiguous memory location. Converting a string to array in java allows for easier processing, which includes extracting individual characters, splitting words, or performing operations like searching and sorting.
Find elsewhere
Top answer
1 of 6
79

You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like

String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
   // Note that this is assuming valid input
   // If you want to check then add a try/catch 
   // and another index for the numbers if to continue adding the others (see below)
   numbers[i] = Integer.parseInt(numberStrs[i]);
}

As YoYo's answer suggests, the above can be achieved more concisely in Java 8:

int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();  

To handle invalid input

You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.

If you don't need to know about invalid input but just want to continue parsing the array you could do the following:

int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
    try
    {
        numbers[index] = Integer.parseInt(numberStrs[i]);
        index++;
    }
    catch (NumberFormatException nfe)
    {
        //Do nothing or you could print error if you want
    }
}
// Now there will be a number of 'invalid' elements 
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);

The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.

Results in

Input: "2,5,6,bad,10"  
Output: [2,3,6,10]

If you need to know about invalid input later you could do the following:

Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)        
{
    try 
    {
        numbers[i] = Integer.parseInt(numberStrs[i]);
    }
    catch (NumberFormatException nfe)   
    {
        numbers[i] = null;
    }
}

In this case bad input (not a valid integer) the element will be null.

Results in

Input: "2,5,6,bad,10"  
Output: [2,3,6,null,10]

You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.

2 of 6
44

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

With the Arrays.stream() alternative as

int [] v = Arrays.stream(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

However much better for parsing bigger chunks of text is

int [] v = Pattern.compile(",\\s+").splitAsStream(line)
  .mapToInt(Integer::parseInt)
  .toArray();  

As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.

See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.

🌐
Baeldung
baeldung.com › home › java › java array › converting a string array into an int array in java
Converting a String Array Into an int Array in Java | Baeldung
January 8, 2024 - In this article, we’ve learned two ways to convert a string array to an integer array through examples. Moreover, we’ve discussed handling the conversion when the string array contains invalid number formats. If our Java version is 8 or later, the Stream API would be the most straightforward ...
🌐
Centron
centron.de › home › tutorials › java string array - tutorial
Java String Array - Tutorial – centron
February 6, 2025 - The second statement is true because when converted to String, their values are the same and String class equals() method implementation checks for values. For more details, please check the String class API documentation.
🌐
Baeldung
baeldung.com › home › java › java string › convert string to string array
Convert String to String Array | Baeldung
January 8, 2024 - String is probably one of the most commonly used types in Java. In this tutorial, we’ll explore how to convert a String into a String array (String[]).
🌐
Baeldung
baeldung.com › home › java › java string › convert an arraylist of string to a string array in java
Convert an ArrayList of String to a String Array in Java | Baeldung
March 7, 2025 - That is to say, at runtime, the array returned by the toArray() method doesn’t know its elements’ concrete types. They could be String, Integer, or even mixed by different types since the Object class is the supertype of all other types.
🌐
Javatpoint
javatpoint.com › how-to-convert-string-to-string-array-in-java
How to convert String to String array in Java
How to convert String to String array in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Software Testing Help
softwaretestinghelp.com › home › java › java string array- tutorial with code examples
Java String Array- Tutorial With Code Examples
April 1, 2025 - In this section, let’s see the various methods to add an element to the string array. In this method, you create an array having a larger size. For Example, if you have to store 5 elements in the array, then you will create an array with size 10. This way you can easily add new elements at the end of the array. An example that implements the addition of an element to the Pre-allocated array is shown below. import java.util.*; public class Main { public static void main(String[] args) { String[] colorsArray = new String[5]; // initial array values colorsArray[0] = "Red"; colorsArray[1] = "Gre
🌐
GeeksforGeeks
geeksforgeeks.org › java › string-arrays-in-java
String Arrays in Java - GeeksforGeeks
October 2, 2025 - So generally we have three ways to iterate over a string array. The first method is to use a for-each loop. The second method is using a simple for loop. And the third method is to use a while loop.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-string-to-string-array
Java Program to Convert String to String Array - GeeksforGeeks
July 23, 2025 - They are as follows: ... Create an array with string type. Split the given string using string_name.split(). Store splitted array into string array. Print the above string array. ... // Java Program to Convert String to String Array // Using ...
🌐
YouTube
youtube.com › watch
How To Convert String To An Array In Java | Java Full Course From Scratch - YouTube
#iballdesigningdeveloper This video is about How To Convert String To An Array In Java | Java Full Course From ScratchYou can find awesome programming lesson...
Published: July 17, 2025
🌐
Reddit
reddit.com › r/javahelp › how to turn string into array
r/javahelp on Reddit: How to turn string into array
May 4, 2021 -

Hello. I need help on turning a string example

String str = "Processor Mouse Power Supply Phone";

into an array of something like

String[][] arr = new String[]

arr[] = new String []{"Processor" , " Mouse" , "Power Supply" , "Phone"}

Also notice the "power supply " has two separate words. Any help is appreciated. Thank you

Top answer
1 of 4
3

If the individual strings might themselves include a comma followed by a space, then this would not be feasible. Multiple String[] arrays could map to the same flat String, and an inverse function would not exist.

However, you note in a comment that your strings cannot include the comma separator. You can split the flat string back into the original substrings, using ", " (comma,space) as a separator.

APIs that support this include the standard Java String.split() method, and Guava's Splitter class.

Here's an example with Java's split() method:

public static void main(String[] args) {
    String[] strs = new String[] { "Foo", "Bar", "Baz" };

    String joined = Arrays.toString( strs );

    String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);

    // String.split()
    String[] resplit = joinedMinusBrackets.split( ", "); 

    for ( String s : resplit ) {
        System.out.println( s );
    }

}

And here's an example with Guava's Splitter class:

public static void main(String[] args) {
    String[] strs = new String[] { "Foo", "Bar", "Baz" };

    String joined = Arrays.toString( strs );

    String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);

    // Guava Splitter class
    List<String> resplitList = Splitter.on( ", " ).splitToList( joinedMinusBrackets );

    for ( String s : resplitList ) {
        System.out.println( s );
    }
}
2 of 4
1

I guess that's the answer you're searching for. Briefly, it's about using serialization with apache codecs for encoding/decoding objects. I don't want to do copy/paste from another answer, so I'll give you only the code sample in case link changes someday. Here it is:

  // serialize
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new ObjectOutputStream(out).writeObject(yourArray);

 //encode
    String encodeString = new String(Hex.encodeHex(out.toByteArray()));

 // deserialize
    ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(yourString.toCharArray()));
    String yourArray = Arrays.toString((String[]) new ObjectInputStream(in).readObject());
}
// And then you could use `String#split()` method to convert string to array.

Another option is to use something like Gson JSON library, with Gson, you can convert any java object to a json string and then convert it back. Example code may looks like this:

//Put an array (or any other object to gson object
Gson gson = new Gson();
String json = gson.toJson(yourArray);

// Retrieve your object from gson
Gson gson = new Gson();
Array array = gson.fromJson(json, Array.class);

For more details you look this article.

🌐
How to do in Java
howtodoinjava.com › home › java array › convert string to string array in java with split()
Convert String to String Array in Java with split()
February 22, 2023 - Convert String to String array in Java with split(), handle regex delimiters, empty strings and emoji, and build a single-element array.