In Java, a String is a sequence of characters. It is a built-in class that represents a series of characters, and is widely used for storing and manipulating text in Java programs. Strings are immutable, meaning that their values cannot be changed once they are created.
An array in Java is a collection of values of the same type that are stored in contiguous memory locations. Arrays in Java have a fixed size, which is determined when the array is created, and each element in the array can be accessed using an index.
Converting a string to an array in Java means transforming a string, which is a sequence of characters, into an array of individual characters or sub-strings.
Why Converting String To Array in Java is required
Converting a String to an array in Java can be useful in many situations and this is required because:
- Parsing input: When you receive input as a String, you may need to parse it into individual components for further processing.
- Manipulating text: If you need to manipulate individual characters or sub-strings within a larger text string, it can be useful to convert the String to an array of characters or sub-strings. This allows you to access and modify individual elements of the string more easily.
- Storing data: If you need to store a collection of values that have a fixed size, an array can be a convenient data structure.
- Passing data between methods: In some cases, it may be more convenient to pass data as an array rather than as a String.
Methods for Converting String To Array in Java
- toCharArray()
- split()
- getBytes()
- StringTokenizer()
Let’s find out complete code and explanation of each approach for converting string to array in java:
Approach 1: Converting String To Array In Java Using toCharArray() Method
This method creates an array of characters from the String. It returns an array of type char[]. It is an example of converting a String to an array using the toCharArray() method in Java:
Code:
public class StringToArrayExample {
public static void main(String[] args) {
// Declare a String variable
String str = "Hi, Steve!";
// Convert the string to a char array using the toCharArray() method
char[] charArray = str.toCharArray();
// Print the char array
System.out.println("Char array: ");
for (int i = 0; i < charArray.length; i++) {
System.out.print(charArray[i] + " ");
}
}
}
Output:
Char array:
H i , S t e v e !
Explanation of the code:
- Declare a String variable called str and assign it the value “Hello, world!”.
- Call the toCharArray() method on the str variable to convert it to an array of characters. The resulting array is assigned to the charArray variable.
- Use a for loop to iterate over each element in the charArray and print it out, separated by a space. The loop runs from index 0 to index charArray.length – 1.
- Output the resulting array to the console.
Approach 2: Converting String To Array In Java Using split() Method
This method creates an array of substrings by splitting the String based on a delimiter. It returns an array of type String[]. Here is an example of converting a String to an array using the split() method in Java:
Code:
public class StringToArrayExample {
public static void main(String[] args) {
// Declare a String variable
String str = "apple,banana,orange";
// Split the string into an array using the split() method
String[] strArray = str.split(",");
// Print the resulting array
System.out.println("String array: ");
for (int i = 0; i < strArray.length; i++) {
System.out.print(strArray[i] + " ");
}
}
}
Output:
String array:
apple banana orange
Explanation of the code:
- Declare a String variable called str and assign it the value “apple,banana,orange”.
- Call the split() method on the str variable to split it into an array of substrings based on the delimiter. The resulting array is assigned to the strArray variable.
- Use a for loop to iterate over each element in the strArray and print it out, separated by a space. The loop runs from index 0 to index strArray.length – 1.
- Output the resulting array to the console.
Approach 3: Converting String To Array In Java Using getBytes() Method
This method creates an array of bytes from the String. It returns an array of type byte[]. It is an example of converting a String to an array using the getBytes() method in Java:
Code:
public class StringToArrayExample {
public static void main(String[] args) {
// Declare a String variable
String str = "Hello, world!";
// Convert the string to a byte array using the getBytes() method
byte[] byteArray = str.getBytes();
// Print the byte array
System.out.println("Byte array: ");
for (int i = 0; i < byteArray.length; i++) {
System.out.print(byteArray[i] + " ");
}
}
}
Output:
Byte array:
72 101 108 108 111 44 32 119 111 114 108 100 33
Explanation of the code:
- Declare a String variable called str and assign it the value “Hello, world!”.
- Call the getBytes() method on the str variable to convert it to an array of bytes. The resulting array is assigned to the byteArray variable.
- Use a for loop to iterate over each element in the byteArray and print it out, separated by a space. The loop runs from index 0 to index byteArray.length – 1.
- Output the resulting array to the console.
Approach 4: Converting String To Array In Java Using StringTokenizer() Method
This class is used to split a String into tokens based on a delimiter. It returns an array of type String[]. This is an example of converting a String to an array using the StringTokenizer class in Java:
Code:
import java.util.StringTokenizer;
public class StringToArrayExample {
public static void main(String[] args) {
// Declare a String variable
String str = "apple,banana,orange";
// Create a new StringTokenizer object with the string and delimiter ","
StringTokenizer st = new StringTokenizer(str, ",");
// Count the number of tokens (i.e. substrings) in the string
int numTokens = st.countTokens();
// Create a new String array to hold the substrings
String[] strArray = new String[numTokens];
// Use a loop to iterate over the tokens and add them to the array
int i = 0;
while (st.hasMoreTokens()) {
strArray[i++] = st.nextToken();
}
// Print the resulting array
System.out.println("String array: ");
for (i = 0; i < strArray.length; i++) {
System.out.print(strArray[i] + " ");
}
}
}
Output:
String array:
apple banana orange
Explanation of the code:
- Declare a String variable called str and assign it the value “apple,banana,orange”.
- Create a new StringTokenizer object called st with the str variable and delimiter ,.
- Call the countTokens() method on the st object to count the number of tokens (i.e. substrings) in the str variable.
- Create a new String array called strArray with the length of the number of tokens.
- Use a while loop to iterate over the tokens in the st object and add them to the strArray.
- Print the resulting array to the console.
Best Approach for Converting String To Array In Java
‘toCharArray()’ method is considered as best approach for converting a string to an array in Java because of following reasons:
- Simplicity: The toCharArray() method is a simple and straightforward way to convert a string to an array of characters. It only takes one line of code to perform the conversion.
- Efficiency: The toCharArray() method is a relatively efficient way to convert a string to an array, as it avoids creating a new string object and instead directly converts the string to an array of characters.
- Compatibility: The toCharArray() method is compatible with all versions of Java, as it has been a part of the language since the beginning.
- Flexibility: Once you have converted a string to an array of characters, you can easily manipulate and access individual characters in the array using array indexing.
- Consistency: Using the toCharArray() method provides a consistent way to convert a string to an array, as it is a standard method that is used across many Java applications.
Sample Problems for Converting String To Array In Java
Sample Problem 1
Write the code for converting string to array in Java with by implementing toCharArray() method with string value = ‘Cat, Dog, Bird’
Solution:
- Declare a String variable value with the value “Cat, Dog, Bird”.
- Use the toCharArray() method to convert the string value to an array of characters. This is done by calling the toCharArray() method on the value string and storing the result in a new char[] array called charArray.
- Print each character in the charArray array using a for loop that iterates through the array and prints each character using System.out.println().
public class StringToArrayExample {
public static void main(String[] args) {
String value = "Cat, Dog, Bird";
// Use toCharArray() method to convert string to array
char[] charArray = value.toCharArray();
// Print each character in the array
for (int i = 0; i < charArray.length; i++) {
System.out.println("charArray[" + i + "] = " + charArray[i]);
}
}
}
Output:
charArray[0] = C
charArray[1] = a
charArray[2] = t
charArray[3] = ,
charArray[4] =
charArray[5] = D
charArray[6] = o
charArray[7] = g
charArray[8] = ,
charArray[9] =
charArray[10] = B
charArray[11] = i
charArray[12] = r
charArray[13] = d
Sample Problem 2
Write the code for converting string to array in Java by using split() method by assuming that string value = ‘Fruits’.
Solution:
- We start by defining a public class named StringToArrayExample.
- Inside the class, we define the main method which serves as the entry point for the program.
- We create a string variable named value and initialize it to the value of “Fruits”.
- We then use the split() method on the input string value to split it into an array of individual characters. In this case, we use an empty string “” as the separator to split each character individually.
- The resulting array is stored in a new string array variable named array.
- We then use a for loop to iterate over the elements of the resulting array and print each element to the console using System.out.println().
- The loop runs until it reaches the end of the array.
public class StringToArrayExample {
public static void main(String[] args) {
// Define the input string
String value = "Fruits";
// Split the input string into an array using the split() method
String[] array = value.split("");
// Print the elements of the resulting array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Output:
F
r
u
i
t
s
Sample Problem 3
Write the code for converting string to array in Java by using getBytes() method where string value = ‘orange, apple, banana’.
Solution:
- We start by defining a public class named StringToArrayExample.
- Inside the class, we define the main method which serves as the entry point for the program.
- We create a string variable named value and initialize it to the value of “orange, apple, banana”.
- We then convert the input string value to a byte array using the getBytes() method.
- We create a new string variable named newString from the byte array.
- We then use the split() method on the new string newString to split it into an array of individual strings. In this case, we use the separator “, ” to split the string at the comma and space.
- The resulting array is stored in a new string array variable named array.
- We then use a for loop to iterate over the elements of the resulting array and print each element to the console using System.out.println().
- The loop runs until it reaches the end of the array.
public class StringToArrayExample {
public static void main(String[] args) {
// Define the input string
String value = "orange, apple, banana";
// Convert the input string to a byte array using the getBytes() method
byte[] byteArray = value.getBytes();
// Create a new string from the byte array
String newString = new String(byteArray);
// Split the new string into an array using the split() method
String[] array = newString.split(", ");
// Print the elements of the resulting array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Output:
orange
apple
banana
Sample Problem 4
Write the code for converting string to array in Java by using StringTokenizer() method with string value = ‘Toyota, Suzuki, Hyundai’.
Solution:
- We start by importing the StringTokenizer class from the java.util package.
- We define a public class named StringToArrayExample.
- Inside the class, we define the main method which serves as the entry point for the program.
- We create a string variable named value and initialize it to the value of “Toyota, Suzuki, Hyundai”.
- We then create a new StringTokenizer object named st to tokenize the input string value. We use the separator “, ” to tokenize the string at the comma and space.
- We determine the number of tokens in the input string value using the countTokens() method and store the result in an integer variable named count.
- We create a new string array variable named array with length equal to the number of tokens in the input string.
- We then use a for loop to iterate over the tokens and store each token in the string array using the nextToken() method of the StringTokenizer object.
- We then use another for loop to iterate over the elements of the resulting array and print each element to the console using System.out.println().
import java.util.StringTokenizer;
public class StringToArrayExample {
public static void main(String[] args) {
// Define the input string
String value = "Toyota, Suzuki, Hyundai";
// Create a new StringTokenizer object to tokenize the input string
StringTokenizer st = new StringTokenizer(value, ", ");
// Determine the number of tokens and create a new string array to store them
int count = st.countTokens();
String[] array = new String[count];
// Store each token in the string array
for (int i = 0; i < count; i++) {
array[i] = st.nextToken();
}
// Print the elements of the resulting array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Output:
Toyota
Suzuki
Hyundai
Conclusion
In Java, converting a string to an array means converting a single string value into an array of characters or an array of substrings based on a specific delimiter.
If you have a string “Hello, World!”, you can convert it to an array of characters, where each character is stored in a separate element of the array. To do this, you can use the toCharArray() method of the String class.
You can also convert a string to an array of substrings by splitting the string based on a specific delimiter. If you have a string “apple,banana,orange” and you want to split it into an array of substrings based on the comma (“,”) delimiter, you can use the split() method of the String class