[java] Adding values to an array in java

int[] tall = new int[28123];

for (int j = 1;j <= 28123; j++){
    int x = 0;
    tall[x] = j;
    x++;
}

What is wrong with this code? Shouldn't this code do the following:

  1. Create an array named tall with a size of 28123.
  2. Make index 0 = 1, index 1 = 2 and so on.

This question is related to java arrays

The answer is


I suggest you step through the code in your debugger as debugging programs is what it is for.

What I would expect you would see is that every time the code loops int x = 0; is set.


You always set x to 0 before changing array's value.

You can use:

int[] tall = new int[28123];

for (int j = 0;j<28123;j++){
    // Or whatever value you want to set.
    tall[j] = j + 1;
}

Or just remove the initialization of x (int x=0) before the for loop.


put x=0 outside the for loop that is the problem


No, you're re-initializing x in every loop. Change to:

int[] tall = new int[28123];
int x = 0;

for (int j = 1;j<=28123;j++){
    tall[x] = j;
    x++;
}

Or, even better (since x is always equal to j-1):

int[] tall = new int[28123];

for (int j = 1;j<=28123;j++){
    tall[j-1] = j;
}

You have not one, but many mistakes. It should be:

int[] tall = new int[28123];

for (int j=0;j<28123;j++){
    tall[j] = j+1;
}

Your code is putting a 0 in all the positions of the array.

Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).


  • First line : array created.
  • Third line loop started from j = 1 to j = 28123
  • Fourth line you give the variable x value (0) each time the loop is accessed.
  • Fifth line you put the value of j in the index 0.
  • Sixth line you do increment to the value x by 1.(but it will be reset to 0 at line 4)

public class Array {
    static int a[] = new int[101];
    int counter = 0;
    public int add(int num) {
        if (num <= 100) {
            Array.a[this.counter] = num;
            System.out.println(a[this.counter]);
            this.counter++;

            return add(num + 1);
        }
        return 0;
    }

    public static void main(String[] args) {
        Array c = new Array();
        c.add(1);
    }
}