JavaChallenge42
Try to solve the challenge by yourself first!
I got surprised when I saw the bytecode of the above code —
public class JavaChallenge42 {
public JavaChallenge42() {
}
public static void main(String[] args) {
int[] arr = new int[5];
int index = 0;
byte var10001 = index;
int index = true;
arr[var10001] = 3;
System.out.println("The value of first element is " + arr[0]);
System.out.println("The value of fourth element is " + arr[3]);
}
}
Before understanding the bytecode, let me tell you the answer which is —
The value of first element is 3
The value of fourth element is 0
Yes, that’s what the answer is. So this challenge is on Java Precedence. Let’s see that —

There are three operators- [], =, = as —
1. arr [index]
2. arr [index]= index
3. index = 3
So according to the precedence table arr[index]
has become arr[0]
because currently index=0; Now there are 2 =
so which one will be evaluated first? So we can get that info from the precedence table itself. In case of =
operator the evaluation happens from Right to Left, so now index=3
evaluated first and now the value of the index
is 3 which will be assigned to arr[0]
. The value arr[3]
is 0 which is a default value of primitive int.