# NullPointerException when accessing an array with objects defined by for loop

So I'm making a SnakeBird-type game with a level editor, and when a new level is created I want it to be made only out of free tiles. I tried making a 2d array and filling it in with tiles, but it doesn't seem to work.

TileGrid.java

public class TileGrid {
private Tile[][] map;
private int w, h;
private Level l;

public TileGrid(int w, int h, Level l) {
this.w = w;
this.h = h;
this.l = l;
this.map = new Tile[this.w][this.h];

for(int i = 0; i < this.map.length; i++) {
for(int j = 0; j < this.map[i].length; j++) {
map[i][j] = new Tile(TileState.FREE, Tile.DEF_TILE_DIM * i, Tile.DEF_TILE_DIM * j, this.l);
}
}
}
}


Tile.java

public class Tile {
public static final int DEF_TILE_DIM = 25;
private int w = DEF_TD, h = DEF_TD, gridX, gridY;
private TileState state; //enum with different states
private Level l;

public Tile(TileState state, int x, int y, Level l) {
this.state = state;
this.lx = x;
this.ly = y;
this.l = l;
}
}


Level.java

public class Level {
public static final int DEF_LW = 32, DEF_LH = 18;
private int lw, lh;
private TileGrid grid;

public Level(int lw) {
this.lw = lw;

if(lw == DEF_LW) {
this.lh = DEF_LH;
} else {
while(this.lw % 16 != 0) {
this.lw++;
}

this.lh = this.lw / 16 * 9;
} //creates an even 16/9 ratio of tiles

grid = new TileGrid(this.lw, this.lh, this);
}
}


A NullPointerException is thrown at the line which creates all the tiles in the TileGrid constructor: (map[i][j] = new Tile(TileState.FREE, ...). It seems like the TileGrid constructor's for() loop isn't actually setting any of the tiles, as I tried to access them separately in another class and it still doesn't recognize any of them. is there a problems with for() loops that I didn't know of or is it just my mistake?

• Which line exactly throws the NPE? Is it possible that anything else in that line is null? Have you tried setting a debugger breakpoint in the line where the NPE occurs and looked at the values of all variables at that point? – Philipp Jul 2 at 12:30
• @Philipp The NPE is thrown at the line which creates all the tiles in the TileGrid constructor (map[i][j] = new Tile(TileState.FREE, ...)). I have no idea how to go about setting breakpoints in this line. – Leonardo Vegetti Jul 2 at 12:51
• When the problem already happens in the constructor, then all the code about updating and rendering seems unrelated to the problem. I removed it from the question in order to not distract any readers. I also added the above information you added to the question. – Philipp Jul 2 at 13:19
• Thanks for the correction, any idea why this happens? – Leonardo Vegetti Jul 2 at 13:20
• Maybe map[i] is null somehow? – trollingchar Jul 3 at 7:59