Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

index value

 
amit patidar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Sheriff
Posts: 48404
56
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Campbell ,

Thank you

and the question is not from any mock exam
 
Campbell Ritchie
Sheriff
Posts: 48404
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome

Now, everybody else, tell me whether I got it wrong!
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use code tags when you post source code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic