January 7, 2010

Array index behavior in Java

int indexFor1D = 3;
int indexFor2D = 1;
int [] array1D = { 5, 6, 7, 8, 9 };
int [][] array2D = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};

System.out.println("From 2D: " + array2D[indexFor2D++][indexFor2D++]);
System.out.println("indexFor2D: " + indexFor2D);

array1D[indexFor1D++] = indexFor1D;
System.out.println("indexFor1D: " + indexFor1D);
System.out.print("New 1D: ");
for(int tmp : array1D)
System.out.print(tmp);


produces output

From 2D: 5
indexFor2D: 3
indexFor1D: 4
New 1D: 56749

No comments:

Post a Comment