First, identify whether you're interested in the 4-connected neighborhood or 8-connected. The 4-connected neighborhood are the cells above, left, right and below a cell. The 8-connected neighborhood are the same cells plus the diagonal.
Now, you just need a way to compute the indices of a particular cell.
Here's an example for computing the column index to the left of another.
int getLeftIndex( int index, int width ) {
int rv = index - 1;
if ( index < 0 ) { index = width - 1; }
return rv;
}
Similar methods can compute the column index to the right, or the row index above or below.
Call two methods to get both the appropriate row and column.
You could also generalize this to provide a single method that accepts a delta in either direction, so that you could loop over the cells.
public static int getCoord( int from, int delta, int size ) {
return Math.floorMod( from + delta, size); // Requires Java 8
}
Java also provides a modulus operator, but it won't give you the results you want.
Here's an example of looping over the 8-connected cells around another:
public static void main(String[] args) {
int x = 0;
int y = 0;
int size = 4;
for ( int i = -1; i <= 1; ++i ) {
for ( int j = -1; j <= 1; ++j ) {
if ( i != 0 || j != 0 ) {
int xij = getCoord( x, i, size );
int yij = getCoord( y, j, size );
System.out.println( "x=" + xij + " y=" + yij );
}
}
}
}