Reputation: 79
I'm still learning about sorting and Arrays. Came up with this code which does sorting letters or numbers on ascending order but I really don't get the last part where System.out.println(SampleArray[i]);
. Why is it SapleArray[i]
? can someone enlighten me please.
public class TestClass {
public static void main(String[] args) {
String SampleArray[] = {"B","D","A","R","Z"};
Arrays.sort(SampleArray);
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
}
}
Upvotes: 0
Views: 94
Reputation: 567
The for
loop does something over and over again.
The first part of the for loop, int i = 0
sets up a variable.
The second part i < SampleArray.length
is the 'terminating condition' - it's the condition that has to remain true before each iteration of the loop.
The last part i++
is what happens after each iteration - i
gets incremented.
So we are printing each element within SampleArray
. i
goes between 0 and the one less than the number of elements in the array. (e.g. if the array contained 4 elements, i
would be 0 to 3, which is what we want).
And in the body of the loop, the [i]
bit selects that element from SampleArray
, and that is the value that gets printed on each line.
Another way of looking at it: SampleArray
supports the []
operator, which when applied, will return an element from the array.
Upvotes: 1
Reputation: 75376
SampleArray
refers to the whole array - here containing five strings.
SampleArray[0]
refers to the first item in the array (here the string "B"
).
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
lets i
take the values 0, 1, 2, 3, 4 one after another, so you print out first SampleArray[0]
and then SampleArray[1]
and so on until all the items have been printed.
Upvotes: 1
Reputation: 295
Going through your code:
first you create a String array with those letters as element, which are saved like this: element 0 of array = B, element 1= D, etc. (in Arrays the counting always begin by 0 and not by 1).
Then it sort it in ascending order.
The for loop is there to print the sorted array, it iterate through the array beginning by element 0, until it is at the last element of the Array and it print these element.
Upvotes: 1
Reputation: 75565
You are trying to print an array, which is an ordered collection of items.
SampleArray[i]
inside the loop lets you access one element at a time, in order.
More specifically, i
takes on the values 0
through 4
in this case.
SampleArray[0]
would give you the first element of SampleArray, because Java uses zero-based indexing for arrays.
Upvotes: 1