| Author |
Evaluation problem
|
Rajesh k Jha
Ranch Hand
Joined: May 10, 2009
Posts: 67
|
|
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
Joined: Mar 24, 2008
Posts: 3670
|
|
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,
|
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
|
 |
Garlapati Ravi
Ranch Hand
Joined: Mar 05, 2008
Posts: 168
|
|
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
|
Ravi Kumar
SCWCD 5 - 89%, SCJP 1.4 - 90%
|
 |
Lucas Smith
Ranch Hand
Joined: Apr 20, 2009
Posts: 804
|
|
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)]
|
SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
|
 |
Rajesh k Jha
Ranch Hand
Joined: May 10, 2009
Posts: 67
|
|
Hi Ravi,
Your example really clarified all my steps of postincrement and preincrement.
Thanks a lot..
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
|
Please Use Code Tags when you post a source code...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
 |
|
|
subject: Evaluation problem
|
|
|