String To Array In Java
Chapter:
Miscellaneous
Last Updated:
11-08-2023 17:20:52 UTC
Program:
/* ............... START ............... */
public class StringToArrayExample {
public static void main(String[] args) {
String input = "apple,banana,orange,grape";
// Split the string using the comma as the delimiter
String[] fruitsArray = input.split(",");
// Print the elements of the array
for (String fruit : fruitsArray) {
System.out.println(fruit);
}
}
}
/* ............... END ............... */
Output
apple
banana
orange
grape
Notes:
-
Java program demonstrates how to convert a single string containing a list of fruits into an array of individual fruit names.
- The program starts with a string input that contains a list of fruits separated by commas: "apple,banana,orange,grape".
- The split() method is used on the input string, with the comma , specified as the delimiter. This method breaks the input string into smaller substrings at every comma occurrence and returns an array of these substrings. In our case, this produces an array with these elements: "apple", "banana", "orange", and "grape".
- The result of the split() method is stored in the fruitsArray variable, which is declared as an array of strings (String[]). Each element of this array holds a separate fruit name.
- A for loop is used to iterate through each element in the fruitsArray. Inside the loop, the current fruit name is printed using the System.out.println() statement. This causes each fruit name to be displayed on a new line.
- In summary, the program demonstrates how to split a string using a delimiter to create an array of substrings, and then it loops through the array to process and print each individual substring, which represents a fruit name in this case.