• 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:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

index value

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

in the program below

1 public static void main(String args[]){
2
3 int array[] = new int[5];
4 int index = 0;
5 array[index] = index = 3;
6 System.out.println(array[0]);
7
}

The output of the program is 3 at line 6.

At line 5 , the value of index is 0 in array[index] , why not it is 3

Please explain
 
Marshal
Posts: 75653
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is this a question from a mock exam? If so, make sure (please) to tell us where it is from.

Probably because Java evaluates expressions from left to right. It starts with array[index], at which point index is 0. Then it tries to assign that value, and assigns it to the value of the expression to the right of the first =.
 
amit patidar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Campbell ,

Thank you

and the question is not from any mock exam
 
Campbell Ritchie
Marshal
Posts: 75653
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome

Now, everybody else, tell me whether I got it wrong!
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use code tags when you post source code.
 
If you two don't stop this rough-housing somebody is going to end up crying. Sit down and read this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic