javaindexoutofboundsexception

Getting array index out of bound exception after spliting a string


After splitting a string if last value of index is there then I am not getting any exception.

public class Digits {

    public static void main(String[] args) {
        String s = "123;456;;;777;000";
        String field[] = s.split(";");
        System.out.println(field.length);
        System.out.println(field[5]);
    }
}

Output is ---> s[5] = 000

public class Digits {

    public static void main(String[] args) {
        String s = "123;456;;;;";
        String field[] = s.split(";");
        System.out.println(field.length);
        System.out.println(field[5]);
    }
}

Output is----> ArrayindexoutofBoundException

I am expecting null value but it is throwing error.


Solution

  • when you use String field[] = s.split(";");, the actual calling method is split(";",0).

     public String[] split(String regex) {
        return split(regex, 0); 
     }
    
     // @param  regex : the delimiting regular expression
     // @param  limit : the result threshold, as described above
     public String[] split(String regex, int limit) {
        ...
     }
    

    when limit=0 and the trailing element of the result list is equal to 0, method split constructs the result by removing the empty elements as follows:

    // Construct result
    int resultSize = list.size();
    if (limit == 0) {
        while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
            resultSize--;
        }
    }
    String[] result = new String[resultSize];
    return list.subList(0, resultSize).toArray(result);
    

    This is the reason for s = "123;456;;;777;000" not getting any exception, but s = "123;456;;;;" get ArrayindexoutofBoundException.

    In conclusion, if you want get "" value, you can assgin limit = -1 or other inegative number (Provided you don't want to limit the scope of the split), for example:

    String field[] = s.split(";", -1);
    String field[] = s.split(";", -2);