The main rule is to remember is the Array is starts with 0.
While .length is returns the actual number of array, so length do not count or start with 0
So, as per your example:
int [] oldArray = {1, 5, 6, 10, 25, 17};
Here in your example below
for(int i = 0; i < oldArray.length; i++){}
The i starts with 0 and loop continue till i value as 5 as you are using < only.
If you try to use <= it will fail again, as you try to assess 7th(0-6) element which is not present.
Now take a another example as below, where we try to reverse a string:
String name="automation";
System.out.println(name.length());
for(int i=name.length()-1;i>=0;i--) {
System.out.print(name.charAt(i));
}
Output:
10
noitamotua
Now in above example if you don't use -1 the value 10 will be pass inside the loop, as the length return 10 as per length of string but for array 10th element not present as array starts with 0 so it require till 9th place only as per above example , if you pass 10 it will throw error as 10th position is not present for it, thats why we need to use -1 at least for decrements(i--) order for sure
odlArray[oldArray.length - 1]
will return17
... – IntemperateoldArray.length
== 6), you access elements from0
through to5
, so the last element willoldArray.length - 1
:D – Intemperatefor(int i = 0; i <= oldArray.length - 1; i++){
for example, but the way you have it is much easier... – Intemperate