• 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

Inconsistent output

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When I run the following in JDK1.2.2, I get the output 1 2. When I run it under JDK 1.4.1, I get the output 1 3. Which is the correct answer and why am I getting different results?
int a = 1;
int b = 1;
a = a++;
b = b++ + b;
System.out.println(a+ " "+b);
Thanks.
Regards,
Kathy
 
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I ran this code using jdk1.2.1 and I got the answer 1 3.
look at line b=b++ +b:
As per operator precedence b++ has the higher precedence and so first
b++ says assign the value of 1 and then increment the value of b to 2.We are then adding b which is already incremented to 2 as per our b++ operator. So to the compiler the above line reads
b=b++(1) +b(2)
 
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why it should not be 2 3?
 
La Vish
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the line is a=a++ which means assign the current value(1) to a and then increment(2).But this incremented value has no where to go!So a still has the value of 1.
The scenario is different if it is a=++a; a will now have the value of 2.
 
reply
    Bookmark Topic Watch Topic
  • New Topic