sid noob wrote:class Twisty {
{ index = 1; }
int index;
public static void main(String[] args) {
new Twisty().go();
}
void go() {
int [][] dd = {{9,8,7}, {6,5,4}, {3,2,1,0}};
System.out.println(dd[index++][index++]);
}
}
Please help me to understand this program, i am unable to understand as to how the output shows as 4 without any errors on running the program.
Regards,
Sid.
Here are the explanations:
You have a class called Twisty. This class has one instance variable "index" which is initialized to ZERO. You start with the "main" method, which creates an instance (or an object) of type "Twisty" at which point the "initialization block (
{ index =1 } ) assigns the value of ONE to index. Right after we are done with the object creation and initialization, we invoke method go();
Method "go()" creates a two-dimensional array (array of arrays) and initializes with the following:{{9,8,7}, {6,5,4}, {3,2,1,0}}
The first sequence of integers (9,8,7) would be index 0, the second one (6,5,4) would be at index 1 and so on.
So, consider you want to get the integer "7" from the first array (9,8,7). You would do that by getting the element at index [0][2]. The ZERO obtains the whole array at index 0 which is {9,8,7}. The TWO obtains the third element from that same array, hence we get integer of value 7.
The
System.out.println(); code prints the element, but you have to be careful with the post-incrementing the index instance variable.
This gives you the answer of 4. Remember post-increment works as follows: use the variable first and then increment.