Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Doubt in array: a [ (a = b)[3] ] enthuware mock test

Indu Acharya
Greenhorn
Posts: 27
1
Can someone explain how this works?
a [ (a = b)[3] ] = 1

Ganesh Patekar
Bartender
Posts: 696
23
Expression evaluation always starts from left so first we get an array

1. a having { 1, 2, 3, 4 }; then

2. ( a = b) is executed where b is assigned to a so now both have same array i.e. { 2, 3, 1, 0 }; but remember the first array pushed on stack at point 1 is { 1, 2, 3, 4 };
From now a and b both points to same array having { 2, 3, 1, 0 };

3. (a = b)[3] means element at index 3 of array having { 2, 3, 1, 0 }; which is pointed by both a and b so the element is 0.

4. Finally we get a[0] where this a is having { 1, 2, 3, 4 }; because It was already pushed on stack by evaluating It, see point 1 so It prints 1.

Indu Acharya
Greenhorn
Posts: 27
1

Ganesh,

I understood the concept you have explained, but when I try to use the same concept for other elements in an array, I am getting different output.
Could you please tell where I am going wrong.

Intially a [] = { 1, 2, 3, 4 } and it is loaded into stack

after assignment a=b,both points to same array
i.e a[] =b[] = {2, 3, 1, 0}

a[(a=b)[3]] => a[a[3]] => a[0] => 1

a[(a=b)[2]] => a[a[2]] => a[1] => 2  this is wrong, it should print 3

a[(a=b)[1]] => a[a[1]] => a[3] => 4  this is wrong, it should print 0

a[(a=b)[0]] => a[a[0]] => a[2] => 3  this is wrong, it should print 1

Henry Wong
author
Sheriff
Posts: 23289
125
Indu Acharya wrote:
Could you please tell where I am going wrong.

Everyone of those lines had a side effect. You seem to assume that those side effects didn't happen -- when you operated on the next line.

Henry

Indu Acharya
Greenhorn
Posts: 27
1
• 1
a[0] = 1 is pointing to original a array, whereas rest
a[1] = 3
a[3] = 0
a[2] = 1
are pointing to b array which was assigned to a.

Henry Wong
author
Sheriff
Posts: 23289
125
Correct. Have a cow for working it out.

Henry

Roel De Nijs
Sheriff
Posts: 11338
177
• 2
I have taken several Java certification exams and I have never encountered this (weird) syntax.

Indu Acharya
Greenhorn
Posts: 27
1
Henry Wong wrote:Correct. Have a cow for working it out.

Thanks alot for the cow.