Java split() Method Explained with Examples

In Java, the split() method is used to split a string by a specified delimiter, and returns a string array.

String str = "Hello,World,Good,Morning";
String[] parts = str.split(",");
for (String part : parts) {
    System.out.println(part);
}

The code above will output:

Hello
World
Good
Morning

The split() method also accepts an optional second parameter to specify the number of splits. If the number is positive, the string will be split from left to right; if the number is negative, the string will be split from right to left.

String str = "Hello,World,Good,Morning";
String[] parts = str.split(",", 2);
for (String part : parts) {
    System.out.println(part);
}

The above code will produce:

Hello
World,Good,Morning
bannerAds