class A { public static void main(String[] args) { int[] a = new int[10]; int b=0; int x; a[a[b]]=a[b]=b=2; System.out.println(a[x]); //What should be the value of x so that it returns non zero value } }

First note that when the int array is created, each element is initialized to zero.

Basically, in a simple assignment, the left-hand operand is evaluated first to figure out exactly where the value of the right-hand expression should be assigned -- for example, a variable or a particular index of an array. In this case, we have...

int b = 0; a[a[b]] = ...

Here, a[b] is a[0], which is 0. So a[a[b]] is also a[0].

And the line a[a[b]] = a[b] = b = 2 essentially becomes a[0] = (a[0] = (b=2)). So the value 2 is assigned to the variable b, which is assigned to a[0], which is assigned to a[0].

Therefore, a[0] is 2, while a[1] through a[9] are all zeros.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org

int[] a = new int[10]; int b=0; int x; a[a[b]]=a[b]=b=2; System.out.println(a[x]);

In the above statement first all the variables are fully evaluated and then the assignment happens that is the statement becomes:

a[0]=a[0]=b=2

Since before this statement b=0 and a[b]=0 and as the question ask for a value x of that will give non-zero value, result becomes 0 b'coz that is the only index position where we've stored 2.

class A { public static void main(String[] args) { int[] a = new int[10]; int b=0; int x; a[a[b]]=a[b]=b=2; System.out.println(a[x]); //What should be the value of x so that it returns non zero value } }

in the above program, the variable i is not initialized. and since its a local variable, it does not get the default value. so this above coding results in a compilation error. variable x might not have been initialized

You've been asked once before to revise your display name to meet the JavaRanch Naming Policy. You can edit your name here. Thank you for your prompt attention!