Assigning array values ​​in a for java loop

I am still starting in java - and any guidance would be great. I basically hope to create an array and then assign values ​​to this array in a for loop. The code I have at the moment is:

int i;
int[] testarray = new int[50];

for (i = 0; i <=50; i++) {  
testarray[i]=i;
}

All I want to do is to make an array with each record with an iteration number (using this method) I know that it is really simple, but I feel like I missed something important while learning the basics! Thank!

+5
source share
3 answers

Everything is fine, except for the stopping condition:

for (i = 0; i < 50; i++) {  

Since your array is 50 in size and indexes start at 0, the last index is 49.

i, ( ) camelCase:

int[] testArray = new int[50];

for (int i = 0; i < testArray.length; i++) {  
    testArray[i]=i;
}
+10

50 , 51 ( 0 50).

:

int[] testarray = new int[50];

for (int i = 0; i < 50; i++) {  
    testarray[i] = i;
}

:

int[] testarray = new int[50];

for (int i = 0; i < testarray.length; i++) {  
    testarray[i] = i;
}
+6

Use array length instead of hardcoding 50.

for (i = 0; i <testarray.length; i++) 
0
source

All Articles