• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Evaluation problem

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can somebody make me understand how the value of j is evaluating in the commented line

class incdec
{
public static void main(String[] args)
{
int j=5;
int k;
k=j++ + --j;// How it is evaluation
k++;
System.out.println("k="+k);
}
}
 
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
With the post increment operator when used in an expression value will be incremented/decremented by one but the previous value is used.
So the line,

can be interpreted as,

 
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
remember this:
post-increment -> participates in expression and then increment
pre-increment -> increment and participate in expression

int j=5;
int k;
k=j++;
System.out.println("k="+k); // prints 5
(or)
int j=5;
int k;
k=++j;
System.out.println("k="+k); // prints 6


j++ + --j;
5 + (6-1)5 = 10



 
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


It's pretty siple - the output is 11.
[value 5 is taken(it's post incrementing so we take j value in this expression and j+1 in the next expression with j) + --j(value 5 is taken - it's predecrementing but j has value of 6 because it was postincremented)]
 
Rajesh k Jha
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ravi,
Your example really clarified all my steps of postincrement and preincrement.
Thanks a lot..
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please Use Code Tags when you post a source code...
reply
    Bookmark Topic Watch Topic
  • New Topic