Reputation: 157
What does [1]
at the end of statement mean?
String magnitudeString = details.split(" ")[1];
Can't it be written like this:
String [] magnitudeString = details.split(" ");
Upvotes: 0
Views: 354
Reputation:
It's index of the String[] array that is returned by details.split(" ")
.
One suggestion use
String [] magnitudeString = details.split(" ");
and iterate through.
using
String magnitudeString = details.split(" ")[1]
may give run time exception of array index out of bound
Upvotes: 0
Reputation: 59617
[1]
is indexing an array: the result of String.split()
is an array, and [1]
is taking the second element from that result.
This is equivalent to:
String strs[] = details.split(" ");
String magnitudeString = strs[1];
So it can't be re-written quite like your suggestion.
Obviously either of these is a problem if the result of split
has fewer than 2 elements, so a length
check before accessing array elements is prudent, and the immediate form won't allow this.
Upvotes: 11
Reputation: 15052
It simply means that the split()
method is going to return an array, and you are assigning the content at the second index of that array to your String magnitudeString
(keep in mind that indexes start from 0 in Java).
Upvotes: 2