I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first comp
Those algorithms are both incorrect because of the comparison:
for( int i = 0; i < elements.length - 1; i++)
or
for(int i = 0; i + 1 < elements.length; i++) {
It's true that the array elements range from 0 to length - 1, but the comparison in that case should be less than or equal to.
Those should be:
for(int i = 0; i < elements.length; i++) {
or
for(int i = 0; i <= elements.length - 1; i++) {
or
for(int i = 0; i + 1 <= elements.length; i++) {
The array ["a", "b"]
would iterate as:
i = 0 is < 2: elements[0] yields "a"
i = 1 is < 2: elements[1] yields "b"
then exit the loop because 2 is not < 2.
The incorrect examples both exit the loop prematurely and only execute with the first element in this simple case of two elements.