How to convert comma separated String into an Array in Java

In this article, we will learn how to convert a comma-separated string into an array.

we can use the split(..) method in the String class to split a java string with any separator. The separator can be a single character string or can be a word.

The below example will show how to convert a comma-separated string into an array and print all individual array elements in the console using for loop.

Code:

/**
 * This is sample programm to convert a comma separated string to an array.
 */
public class CommaStringToArray { 
    public static void main(String args[]) 
    { 
        String colorsRaw = "Green,Yellow,Blue,Grey,Black,Red"; 
        String[] colorsArray = colorsRaw.split(","); 
  
        for (String color : colorsArray) 
            System.out.println(color); 
    } 
}

Output:

Green
Yellow
Blue
Grey
Black
Red