Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Evaluation problem  RSS feed

 
Rajesh k Jha
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • 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);
}
}
 
Vijitha Kumara
Bartender
Posts: 3973
24
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • 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,

 
Garlapati Ravi
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • 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



 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Hi Ravi,
Your example really clarified all my steps of postincrement and preincrement.
Thanks a lot..
 
Ankit Garg
Sheriff
Posts: 9608
36
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please Use Code Tags when you post a source code...
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!