String.split() Basics: Splitting by Delimiter
What you'll learn: How to use split() to break a string into pieces based on a delimiter and work with the resulting array.
What is split()?
The split() method divides a string into multiple parts wherever a delimiter (a separator character or pattern) appears. It returns an array of strings, each containing a piece of the original string.
Think of it like cutting a sandwich: if you cut a sub sandwich at each piece of lettuce, you end up with separate bread sections. The lettuce is your delimiter, and the bread pieces are your array elements.
Basic Usage
String data = "apple,banana,cherry";
String[] fruits = data.split(",");
// Result: ["apple", "banana", "cherry"]
System.out.println(fruits[0]); // "apple"
System.out.println(fruits[1]); // "banana"
System.out.println(fruits[2]); // "cherry"
System.out.println(fruits.length); // 3
The delimiter (, in this case) is removed from the results—only the content between delimiters is kept.
Understanding the Array Structure
String sentence = "Java is great";
String[] words = sentence.split(" ");
// Result: ["Java", "is", "great"]
String path = "home/user/documents";
String[] folders = path.split("/");
// Result: ["home", "user", "documents"]
Each split creates a new String array. The array length equals the number of pieces created, and you access elements using standard array indexing starting at 0.
Empty Strings in Results
String text = "a,,b";
String[] parts = text.split(",");
// Result: ["a", "", "b"]
// Notice the empty string at index 1
When delimiters appear consecutively, split() creates empty string elements between them.
Key Takeaway: split(delimiter) breaks a string into an array wherever the delimiter appears, removing the delimiter itself and preserving the content (including empty strings) between each occurrence.