Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operator assignment

 
velan vel
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai ranchers
can any one expalin the ans for this question

here ans is c


1. public class Q10
2. {
3. public static void main(String[] args)
4. {
5. int i=3;
6. System.out.println(i*=2 + i++);
7. }
8. }
a Program compiles correctly and prints 7 when executed.
b Program compiles correctly and prints 11 when executed.
c Program compiles correctly and prints 15 when executed.
d None of above.
 
Niranjan Deshpande
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i*=2 + i++ ---> evaluation takes place as follows

i=i*(2+ i++)

2+3 is 5. and i is incremented to 4 thus i=4.
thus we now have
i=4*5
thus i=20.

correct me if i am wrong

niranjan
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no nirajan....

Actual answer is C

1. public class Q10
2. {
3. public static void main(String[] args)
4. {
5. int i=3;
6. System.out.println(i*=2 + i++);
7. }
8. }
a Program compiles correctly and prints 7 when executed.
b Program compiles correctly and prints 11 when executed.
c Program compiles correctly and prints 15 when executed.
d None of above.

Here how it goes

i++ means assign the orginal value of i to it and then later increment it .
so
i*=2 + i++)
i=i*(2+i++)
i=3*(2+3)
i=3*5
i=15.

Had it been like this
i*=(2 + ++i)
i=i*(2+ ++i)/// because first increment the original value of i and then assign it to it.
i=3*(2+4)
i=3*6
i=18.

Hope you got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic