-2

Why last line throws ArrayIndexOutofBoundsException while printing the first element of the array?

String t = "www.google.com";
String r[] = t.split(".");
System.out.println(r[0]);
Pshemo
  • 122,468
  • 25
  • 185
  • 269

1 Answers1

0

You can try to use:

String r[] = t.split("\\.");

Escape the . as the dot itself is a special character. The first \ to escape the ., and second \ to escape the first \.

Why last line throws ArrayIndexOutofBoundsException while printing the first element of the array?

Without escaping the special character ., everything is being split. Hence there are no elements to show in r[0], resulting OutOfBoundsException.


Another alternative solution would be:

String r[] = t.split("[.]");
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • @Pshemo Did you downvote my solution? – user3437460 Jan 05 '16 at 19:11
  • Nope, I don't downvote correct solutions. I just can't upvote it either because it is doesn't explain the problem clearly. – Pshemo Jan 05 '16 at 19:12
  • @Pshemo I wonder who downvoted it, I just added an explanation. – user3437460 Jan 05 '16 at 19:13
  • 1
    I can't upvote it because if I wound't know the answer I wouldn't understand how "the dot itself is a special character" (If I would test it with `$` which is also special character I wound't get this error). You may add something about removing trailing empty elements by `split`. – Pshemo Jan 05 '16 at 19:15
  • Considering the question is marked duplicate, I think now posting/correcting/editing solutions makes less sense – Aaditya Gavandalkar Jan 05 '16 at 19:16
  • 3
    Your answer is now wrong. :) Actually, **everything** is split, hence empty array. – Dragan Bozanovic Jan 05 '16 at 19:21
  • @DraganBozanovic If everything is split, shouldn't the token array size be equal to the string length? :) – user3437460 Jan 05 '16 at 19:24
  • No, the token used as the split expression is removed. _The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string._ :) :p :D – Sotirios Delimanolis Jan 05 '16 at 19:25
  • @user3437460 No, because all trailing empty strings are removed. Try `t.split(".", 1)` and see what happens. :) – Dragan Bozanovic Jan 05 '16 at 19:25
  • @SotiriosDelimanolis This is getting intriguing but don't understand the things you said and I like those funny faces of yours :) – user3437460 Jan 05 '16 at 19:29
  • 3
    I quoted the javadoc. The array returned by `split` only contains the values around the expressions used to split the content. So if you split `aaa` on `a`, it would contain nothing. – Sotirios Delimanolis Jan 05 '16 at 19:30