• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

From deepak's mock

 
sudha
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
This is from deepak's mock
Consider the following code :

1. int [ ] a = new int[ 2 ];
2. int b = 1;
3. a[b] = b = 0;

Value will be stored in what element of array a.
A.a[1]
B.none
C.a[0]
Answer given was a[1]
How can it be a[1].I didn't get this.Can any of you please explain.
Regards
Sudha
 
Bin Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should know the evaluation order of an expression.
this order is from left to right.
use your example:
1. int [ ] a = new int[ 2 ];
2. int b = 1;
3. a[b] = b = 0;
at line 3,first a[b] is evaluated.now b is 1,so a[b] is a[1].
now you can see it's a[1] that is being assighned a value.
hope this may clear your doubt.
Bin Zhao
 
madhumathi k
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[] gets precedence over =
 
rajesh dalvi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the same example explained in RHE chapter 2.
The game is all about order of evaluatig expression and operator precedence and associativity.
In this example value will be stored in a[1] and that to 0.
final expression will become a[1] = 0;
How ?
Beacause in java all expressions are evaluated first from left to right.
so after this we will have
a -> a[1]
b -> b (just a reference)
0 -> 0 (literal)
so now expression becomes
a[1] = b = 0;
now associativity of oprators comes in to play.
= operator is evaluated right to left
so expression reduces to
a[1] = b (where now b = 0)
so finaly 0 is assigned to a[1]
Originally posted by sudha:
[B]Hi
This is from deepak's mock
Consider the following code :

1. int [ ] a = new int[ 2 ];
2. int b = 1;
3. a[b] = b = 0;

Value will be stored in what element of array a.
A.a[1]
B.none
C.a[0]
Answer given was a[1]
How can it be a[1].I didn't get this.Can any of you please explain.
Regards
Sudha

 
Adeeshwar Singhal
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was the wonderful explanation Rajesh. Where did u get it. Actually I want to delve a bit more into evaluation of expressions.
I knew the funda but couldn't get it documented anywhere.
Hope to hear from u soon.
 
Mapraputa Is
Leverager of our synergies
Sheriff
Posts: 10065
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sudha and madhumathi k,
may I ask you to register with proper names?
You can read this post for more details. We are glad to see you here, just a little formality´┐Ż
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic