+ 2

Why is it now that in the for loop "x<myArr.length" not "x<=myArr.length"? Why does it show a error when implemented?

public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }

28th Feb 2017, 11:00 PM
Wildman Fizat
Wildman Fizat - avatar
3 Antworten
+ 9
the arrays always start from index 0 and end in length-1, so when the code says <=...length you have an indexOutOfRange exception, you shoul keep the < only or use ...length-1
28th Feb 2017, 11:15 PM
C.E.
C.E. - avatar
+ 4
The elements of ur array starts at 0 and go thru 3. myArr.length=number of elements=4, which is out of range of the array, when using <=
28th Feb 2017, 11:32 PM
Hsn
Hsn - avatar
0
Because the index of an array starts with 0
14th Mar 2017, 11:46 PM
Nabeel Asheer
Nabeel Asheer - avatar