question

P

parwal.sandeep

hello grp !!!
i've one question plz excuse if it is silly to ask !!


public static void main( String[] args )
{
int i=10;
i = i++;
SOP (i);
}


why it is printing 10 instead of 11 ??
 
L

Lasse Reichstein Nielsen

int i=10;
i = i++; ....
why it is printing 10 instead of 11 ??

Because that's what you ask it to do (I assume SOP is a shorthand
for System.out.print).

Execution of the assignment expression "i = i++" first evaluates the
right hand side (i++) and then assigns the value to the variable "i".

Evaluation of i++ is defined to
1) take the value of the variable "i".
2) increment the variable "i"
3) return the value from 1), i.e., the *original* value.

So, you assigment does the following:
- take the value of i (10)
- increment i (i is now 11)
- take the original value (10) and assign it to i (i is now 10)

Then you write i, which is, as expected, 10.

You probably want to change "i = i++" into either "i = i + 1" or "i++",
either will do what you expect (increment the value of "i" by 1).

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top