• Post Reply Bookmark Topic Watch Topic
  • New Topic
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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

[simple question]....

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Test {
public static void main(String[] args) {
int i = 2;
int j = (i=3) * i;
System.out.println(j);
}
}
ans:9

Can anybody tell me in detail,why the answer is 9??
thanks for help.
---------------------------
Liao

[This message has been edited by Marilyn deQueiroz (edited August 08, 2001).]
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(i=3) is evaluated first and assigned before evaluated further. Hence the expression becomes j = 3 * 3 = 9
-Sandeep

------------------
www.tipsmart.com
 
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by chao-long liao:
class Test {
public static void main(String[] args) {
int i = 2;
int j = (i=3) * i;
System.out.println(j);
}
}
ans:9
Can anybody tell me in detail,why the answer is 9??
thanks for help.


(), paranthesis, play a great role in mathematical equations
Here it overrides the earlier assignment of i. Assignments normally happen at the last in a equation. (if you remove () you will get j=6).
Since there is a paranthesis, i=3 happens first , so thats a square (ie i*i) resulting 9
HTH
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Similarly if you had

you would see that the answer is 6 because i=2 before the multiplication sign and i=3 after the multiplication sign.
When written the original way, i=3 before the multiplication sign and i still = 3 after the multiplication sign. It doesn't change back to 2 again.
 
If you were a tree, what sort of tree would you be? This tiny ad is a poop beast.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic