Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I try to split the String "1.1" to 2 new Strings:

String[] array = "1.1".split(".");
System.out.println(array[0]);

but I get a java.lang.ArrayIndexOutOfBoundsException.

Why?

share|improve this question
3  
This was asked so many times. For example check out this. –  WonderCsabo Apr 4 at 11:39
    
Fullstop is a special character in regex. So use "1.1".split("\\."). –  Omoro Apr 4 at 11:42
    
BTW, i suggest "1.1".split(Pattern.quote(".")) for these cases, to improve readability. –  WonderCsabo Apr 4 at 11:46
1  
To add something to the useful answers: In fact the split first results in 4 matches, each one being an empty string. The dot matches any character, so the split finds the empty string in front of the first "1", then the empty string between the "1" and the ".", and so on. But according the method's documentation, trailing empty strings are not included in the resulting array. So the resulting string array itself is of length 0. –  Seelenvirtuose Apr 4 at 11:48
add comment

marked as duplicate by Tim B, Gokul Nath, Richard Morgan, Kevin Panko, Mark S Apr 4 at 12:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5 Answers

up vote 6 down vote accepted

split takes a regular expression. The dot character . is used to match any character in regular expressions so the array will be empty unless the character itself is escaped

String[] array = "1.1".split("\\.");
share|improve this answer
2  
+1 for explaining what the dot character is used for (even though it is used here by accident) –  ifLoop Apr 4 at 11:43
add comment

You need to escape the . with \\ so that it is not taken as a regex meta character as split takes a regular expression. You may try like this:

String[] array = "1.1".split("\\.");
System.out.println(array[0]);
share|improve this answer
add comment

try String[] array = "1.1".split("\\.");

share|improve this answer
add comment

you have to use "1.1".split("\\.")

share|improve this answer
add comment

You need to escape dot.

String[] array = "1.1".split("\\.");
System.out.println(array[0]);

If you look into doc you'll find that split method accepts regex.

In regular expressions . mean any Character except new line.

public String[] split(String regex) {
        return split(regex, 0);
    }
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.