Introduction
In this lab, we will learn how to convert a string to an array using Java code. We will be using the split() method of the String class to split a string based on specified delimiter and return an array. By the end of this lab, you will have a clear understanding of how to convert a string to an array in Java.
Create the Java file
Firstly, create a Java file in the ~/project directory using the following command:
touch ~/project/StringToArray.java
Define the class and the main method
Define the class and the main method by adding the following code to your file:
public class StringToArray {
public static void main(String[] args) {
}
}
Define the string to be converted
Define the string that we want to convert by adding the following code inside the main method:
String message = "labex.io is a technical portal";
Convert the string to an array
Now, let's convert the string to an array. We will use the split() method of the String class with space as a delimiter. Add the following code inside the main method:
String[] stringArray = message.split(" ");
Print the array elements
To make sure that the conversion was successful, let's print the elements of the array. Add the following code inside the main method:
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
Compile and run the code
Save the file by pressing Ctrl+O and then exit by pressing Ctrl+X. Now, compile and run the code using the following commands:
javac StringToArray.java
java StringToArray
You should see the output as:
labex.io
is
a
technical
portal
Convert a URL string to an array
Let's take another example where we have a URL string and want to get it as an array. In this case, we will use '/' as a delimiter. Add the following code inside the main method:
String url = "labex.io/tutorial/java/string";
String[] urlArray = url.split("/");
Print the URL array elements
To confirm the conversion, let’s print the elements of the URL array. Add the following code inside the main method.
System.out.println("\nURL elements:");
for (int i = 0; i < urlArray.length; i++) {
System.out.println(urlArray[i]);
}
Compile and run the code
Save the file by pressing Ctrl+O and then exit by pressing Ctrl+X. Now, compile and run the updated code using the following commands:
javac StringToArray.java
java StringToArray
You should see the output as:
labex.io is a technical portal
labex.io
is
a
technical
portal
URL elements:
labex.io
tutorial
java
string
Summary
In this lab, we have learned how to convert a string to an array using the split() method of the String class in Java. We first defined the string that we want to convert. Then, we used the split() method with space as the delimiter to convert the string to an array. Finally, we compiled and ran the code to get the output. We also learned how to convert a URL string to an array by using '/' as a delimiter.



