• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

[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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic