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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Liutauras Vilda
• Campbell Ritchie
• Tim Cooke
• Bear Bibeault
• Devaka Cooray
Sheriffs:
• Jeanne Boyarsky
• Knute Snortum
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Ganesh Patekar
• Stephan van Hulst
• Pete Letkeman
• Carey Brown
Bartenders:
• Tim Holloway
• Ron McLeod
• Vijitha Kumara

# Order of evaluation of equality operator

Ranch Hand
Posts: 205
Hi,
I am having a doubt that, What is the order of evaluation of equality operator. I feel it is from right to left. Please go through the below code,
1. int a[]={2,2};
2. int b=1;
3. a[b]=b=0;
System.out.println(a[0]);
System.out.println(a[1]);
Now at line 3, which array element value will be assigned to 0.
I got output as 2, 0. I expected 0,2.
In line 3, why a[b] is evaluated before b=0.
Thanks,

Ranch Hand
Posts: 384
hi,
1. int a[]={2,2}; //element 0 = 2, and element 1 = 2
2. int b=1; //regular assignment of b = 1
3. a[b]=b=0; //element 1 is assigned to 0
System.out.println(a[0]); //prints 2
System.out.println(a[1]); //prints 0
remember that all arrays start at element 0
so:
int []d = {5,4,3,2,1,0};
has 6 elements,
at element 0,1,2,3,4,5
the values 5,4,3,2,1,0
I hope this helps you to understand why you got the answer you did
Davy
[ February 22, 2004: Message edited by: Davy Kelly ]

blacksmith
Ranch Hand
Posts: 979
Hi there,
The problem is not in the index, it's in the order
of assignment especially on line 3 of the code
snippet.

I am having a doubt that, What is the order of evaluation of equality operator. I feel it is from right to left. Please go through the below code,
1. int a[]={2,2};
2. int b=1;
3. a[b]=b=0;
System.out.println(a[0]);
System.out.println(a[1]);
...

In the expression of line 3 the array subexpression
is evaluated first, therefore the subsequent assignment
of the value 0 will be for a[1], hence the result
a[0] = 2 and a[1] = 0;
See for more details the JLS 15.26.1 Simple Assignment
Operator =.
HTH, greetings,
Gian Franco Casula
[ February 22, 2004: Message edited by: Gian Franco Casula ]
[ February 22, 2004: Message edited by: Gian Franco Casula ]

Narasimha Rao B.
Ranch Hand
Posts: 205
Hi Gian,
Just now i gone through the JLS, i got the complete picture.
Thanks a lot.
Narasimha.

Ranch Hand
Posts: 90
I just found this bug, if someone's interested in doing some more research:
http://www.ergnosis.com/java-spec-report/java-language/jls-15.26.1.html