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]);
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]);
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("[.]");