1

I have this code:

public static int MAX;
public static int MIN;


public static void startGame(){

    MIN = -1;

    MAX = 1;

    int[] randomGridVals = new int[ROWS*COLUMNS];

    fill(randomGridVals);

    System.out.println(Arrays.toString(randomGridVals));

    <MORE CODE>
}

private static void fill(int[] randomGridVals) {

    for(int i = 0 ; i < randomGridVals.length; i++)
    {
        int rnd = MIN + (int)(Math.random() * ((MAX - MIN) + 1));

        randomGridVals[i] = rnd;
    }

}

I expect that the array is passed by reference and the array have random values in it however when I try to print it its empty. Why is this happening ?

Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169

3 Answers3

4

Hard to say for sure from the code you have provided. I would check the value of ROWS*COLUMNS. That is probably 0 and thus you create a 0 sized array.

MAK
  • 26,140
  • 11
  • 55
  • 86
  • I am sure the constants are fine since I use them to construct a grid. – Cemre Mengü Jan 27 '12 at 23:52
  • 2
    Since the code prints [], that's proof that ROWS*COLUMNS = 0. – user949300 Jan 27 '12 at 23:54
  • 2
    @Cemre - when do you set ROWS and COLUMNS. They really should be set at declaration, since they are all caps and that means "static final". My guess is that you set them _after_ running this routine. – user949300 Jan 27 '12 at 23:55
2

Java is never pass by reference. It's always pass-by-value.

As for being empty, please post ROWS and COLUMNS or check them.

Community
  • 1
  • 1
zw324
  • 26,764
  • 16
  • 85
  • 118
1

Where are you defining ROWS and COLUMNS? At least one of them must equal 0, rendering your data structure an int[0].

Since int is a primitive type, your array starts out filled with 0s. Since arrays can't be resized, and Arrays.toString will print every cell (it won't just skip 0s- 0 is usually pretty important in an int[], for one thing!), this result cannot be an artifact of your array not being written into. It must have been initialized to length 0, and that means that ROWS * COLUMNS == 0. Check the value of ROWS, of COLUMNS, and also their types- surprising types other than int might in rare cases cause this, but the 0 is more likely.

Adam Norberg
  • 3,028
  • 17
  • 22