• 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

Operator Precedence

 
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Everyone,

Please go through the code below...

public class Main {
public static void main(String[] args) {
int x = 0;
x =x++;
x =x++;
x =x++;
System.out.println(x);
}
}

Here x is printed as 0. I don't understand why this is happening.
In my opinion, I feel that since Unary postfix operator(++ ) precedes over assignment operator(=), so the value of x is evaluated from left to right so i feel that value will be incremented every time, and the value of x finally would be 3.

I think i am missing concept here, can any one explain me why 0 is printed.

Thanks in Advance.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Read Corey's Tip Line article, and then try to understand your code one more time.
 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello vishnu,
u have to understand the effect of using the unary postfix
operator.

when we use postfix operator(++) the value of the variable
is incremented after the expression is evaluated.

the right hand variable 'x'is incremented only after the
initial value to x is assigned to the left hand variable 'x' .thus the
incremention doesn't come into effect in the given problem.so each time
the value of variable 'x' in the given expression is evaluated to
0(zero).

hope this helps
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic