Forums Register Login

Order of evaluation of equality operator

+Pie Number of slices to send: Send
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.
Please clarify my doubt.
Thanks,
+Pie Number of slices to send: Send
hi,
in your code:
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 ]
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
Hi Gian,
Just now i gone through the JLS, i got the complete picture.
Thanks a lot.
Narasimha.
+Pie Number of slices to send: Send
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
On my planet I'm considered quite beautiful. Thanks to the poetry in this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 511 times.
Similar Threads
doubt
The shift >> doubt .......................
Doubt........
array doubt: a [ (a = b)[3] ]
Operator precedence and arrays
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:38:19.