This week's book giveaway is in the OCAJP 8 forum.We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!

# Array expression evaluation

ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
Source: Enthuware v4

In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated.

I m not getting this concept.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy!
What is
a [ (a = b)[3] ] ?

It is the (a = b)[3] -th element of array a.

With a = b, the variable a now points to the array object of the second line (where also b points to).
so (a = b)[3]
points to the 3 rd element of the b array. The zero.

The total expression
a [ (a = b)[3] ]
is the same as
a [0]

But didn't we reassign a to b in the inner part?
Yes, but:

In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated.
.
The chosing of array a has been done before the reassignment inside the brackets. Therefore the one and not the two is printed.

By the way, after that line the reassignment will be valid for following code.

prints
1
1
2

Yours,
Bu.

all events occur in real time
Gautam Pandey
Greenhorn

Joined: Sep 21, 2007
Posts: 21

I agree with the above explanation , but when i first look at the code , i took it this way
(a = b)[3] ==> a[3]=b[3] ==> a[3]=0 ==> 0
so a [ (a = b)[3] ] ==> a[0]
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Originally posted by Gautam Pandey:

I agree with the above explanation , but when i first look at the code , i took it this way
(a = b)[3] ==> a[3]=b[3] ==> a[3]=0 ==> 0
so a [ (a = b)[3] ] ==> a[0]

(a = b)[3] ==> a[3]=b[3]
No, here is the mistake. You don't reassign individual elements of the arrays with (a=b)[3]

Yours,
Bu.
Gautam Pandey
Greenhorn

Joined: Sep 21, 2007
Posts: 21
Got it !
The (a=b) is evaluated first then the index [3] is applied to the new reference array (now a is pointing to b) so now it's a[3] which is actually b[3]
Kumar Khiani
Ranch Hand

Joined: Aug 24, 2013
Posts: 40

Thanks for the wonderful explanation

Oracle Certified SQL Expert
OCEWCD 6, OCPJP 7, OCAJP 7

I agree. Here's the link: http://aspose.com/file-tools

subject: Array expression evaluation