Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Assignment

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int array[] = new int[5];
int index = 0;
array[index] = index = 3; // 1st element get assigned to 3, not the 4th element
Can anyone explain me this, i thought the answer was
array[3] = 3.
answer is array[0] =3;
but its wrong.
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sai,
This is just really an example showing operator precedence. In the line:
array[index] = index = 3;
the [] operator has the highest precedence:
Step 1: array[0] = index = 3;
Next we are just left with assignment operator which works from right to left:
Step 2: array[0] = (index = 3);
Step 3: array[0] = 3
Done with array[0] = 3 and index = 3!
Regards,
Manfred.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is it because of operator precedence ? I thought it is a case of Evaluation order and Assignment order rule. Evaluation order is from left to right; so array(index) get evaluated first, and at that time since index had a value 0 the first element of the array is picked up.
Then because assignment order is from right to left, 3 is assigned to index first and then that value of index is assigned to array(0).
Also, is [] an operator ? I think it is not.
Please correct me if I am confusing others with wrong understanding.
Thanks.
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
JLS �3.11, and �3.12 list 'separators' and 'operators'. Eventhough () and [] are called separators, they have high precedence over any operators. Because of that, they are always listed with operators in order of precedence in all books I have seen. Any how, because "[]" has the same highest precedence as "()", it is evaluated first.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic