[SOLVED] Why this .split resulting in array out of bound error?

Issue

public class test {
    public static void main(String[] args) {        
        String[] arr = {"0 1.2.3.4","a b.c.d.e"};
        System.out.println(arr[0].split(".")[2]);
    }
}

I am using java 8.

the expected output is 3.

Solution

The argument to split is a regular expression, not a literal ‘this is the string you should scan for’. The . symbol in regex means ‘anything’, so it’s like " ".split(" ") – the string you’re passing is all separators, hence, you get no output.

.split(Pattern.quote(".")) will take care of it.

EDIT: To go in some detail – given that the string consists of all separators, split initially provides you with an array filled with empty strings; one for each position ‘in between’ any character (as each character is a separator). However, by default split will strip all empty strings off of the end, hence you end up with a 0-length string array.

Answered By – rzwitserloot

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *