How Post Increment operator actually works in JAVA

Ohk,So let me give you one code snippet guess the output if you are correct then you don't need to look further because your concept about the topic is clear well enough :) ,But incase if you can't get the right answer then go through this post it really helps you.

public class TestPostIncrement{
 public static void main(String args[]){
  int j=0;
  for(int i=0;i<100;i++){ 
    j=j++;
  }
  System.out.println(j); 
}
So what is your answer?

The output will be all zeros.... :)

All magic is happened at line j=j++; .

According to JAVA documentation assignments of this form:
lhs = rhs++;
is similar to doing something like this:
temp = rhs;
rhs = rhs+1;  // increment
lhs = temp;   // then assign
 So in our example, line
j=j++;
will be interpreted as:
temp=j;
j=j+1;
j=temp;
and in every iteration it will assign old value to variable j and gives u all zeros.

Plz post any comment as well as any suggestion to improve future posts....

0 comments :

Post a Comment