Post increment operator i++

I can't seem to figure out why the following is outputting 2,2,3 and not 2,3,4. Having searched the Java Language Spec and reading ... (http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#39438)
... it is still not clear. The key line probably is "The value of the postfix increment expression is the value of the variable before the new value is stored." I still think that the second output should have been 3 and not 2. Could someone explain this to me? Thanks.
Here is the code that I tried:
int i;
i = 2;
System.out.println(i);
i = i++; // the line which I don't understand
System.out.println(i);
i++;
System.out.println(i);

The key is to understand the difference between the
value of the expression and the value of the
variable.
i = i++;What that particular bit of devil-spawn does is
this:
1) Get the current value of i. The value of the
postfix increment expression is the value of the
variable before the new value is stored. So we
have to get the "before it's incremented" value. This
is the value of the expression i++.
2) Increment i. This doesn't alter the value of the
expression that was obtained in step 1.
3) Take the value of the expression that was
retrieved in step 1 (the value of i before being
incremented) and stuff it into i.
If you had int i = 2;
int j;
j = i++; Would you expect j to be 2 or 3? It will be 2. And
the same reason that j is 2 here makes i 2 if you put
i on the left of the equals.When the expression is "i = i + 1" compiled, it should be divided into two sub expressions :
1.) i = i; //As postfix defination says use value first and then increment
2)i = i + 1//Increment i;
so, accordingly, the value of i after first step should be 0 and then after second step it is 1(C,C++ behaviour).
so, the statement i = i++ must result into the value 1 for i, not 0.
even in C#.net the value of i is 0 after the execution of above statement.

Similar Messages

  • Post Increment Operator Question

    I had written a small program to test the working of Post increment operator.
    public static void main(String[] args)
         int a = 4;
         a = a++;
         System.out.println ( a );
    I expected the output to be '5', but the output given is '4'.
    Can anyone tell me to how this works in Java ?

    There is a big difference between a++ and ++a.
    a++ means increment a AFTER you have performed the line.
    ++a mean increment a BEFORE you perform the line.
    class Test
    public static void main(String[] args)
    int a = 4;
    a = ++a; //returns a = 5
    // a = a++; //returns a = 4
    //a++; //returns a = 5
    //++a; //returns a = 5
    System.out.println ( a );
    }

  • Behaviour of post increment/decrement operator

    int i = 1;
    i = ++i;
    System.out.println( i ); //output is 2
    i = i++;
    System.out.println( i ); // output is 2, WHY?

    Well, it seems that you didn't get the point at all.
    I know how to do the increment operation. What I
    intended to know is the behavior in this scenario.
    And you got that in reply 2.I assumed the answer to be that. but i was only trying to be sure.
    I know that such codes r not in common use and they are meaningless too, but such codes do come up in various quizzes, etc. to test ur knowledge. we always learn WHAT not to do, but we seldom try to know WHY not to do it. in our endeavor to learn advanced topics we tend to ignore the basics.
    Coming back to the original code can someone tell me whether this is a well defined behavior unlike c/c++ where the behavior of such codes are undefined. as far as i know java is a strongly typed language, where ambiguities have been eliminated (believe i am not wrong on this). Can i expect the same results on all compilers??
    and i hope that the forum behaves in a sane manner in future. Instead of blatantly dismissing a post, let people give reasons for it.
    Thanks

  • Difference between Pre and Post Incrementing a variable

    I have a problem understanding the nuances between i++ and ++i.
    I have run several loops and changed the position of the "++". I noticed that sometimes the out put differs and sometimes the output remains the same.
    Is there a rule of thumb as to whether a variable show be post or pre incremented?
    Thanks

    Thank you all.
    After I asked the question, I did a little research and found this (from JGuru shortcourse):
    Note that x++ and ++x are equivalent in standalone contexts where the only task is to increment a variable by one,that is, contexts where the ultimate evaluation is ignored:
    int x = 4;
    x++; // same effect as ++x
    System.out.println("x = " + x);
    This code produces the output:
    x = 5;
    The next part after this is:
    In the following context, the placement of the increment operator is important:
    int x = 4;
    int y = x++;
    int z = ++x;
    System.out.println(
    "x = " + x + " y = " + y + " z = " + z);
    This code produces the output:
    x = 6 y = 4 z = 6
    ======================================================================
    I thought the out put would be x = 4, y = 6, z = 4.
    I totally lost! How do I interpet this correctly?

  • Row-Based Only option for post processing operator

    Hi,
    Have a question on the role of the "Row-base Only" option for post processing operators. I am trying to understand how a post-processing operation can be done in a row-based mode. A coded PLSQL procedure in a post processing operator is expected to run only once. So I am not clear on how this option might affect the execution of the transformation. Any clarifications would be appreciated.
    Thanks,
    Mazen

    Hi Carsten,
    My question is more on what is the use of the "Row-based only" checkbox that shows up in the properties window for a post-processing operator. How does this checkbox affect the execution of the post-processing transformation?
    Regards,
    Mazen

  • Pre/Post increment query

    I have a query regarding Pre/Post increment.
    The following code:
    int x = 0;
    int y = 0;
    x += y++;
    System.out.println("x = " + x);
    System.out.println("y = " + y);
    Produces the following output:
    x = 0
    y = 1
    (Value of y is assigned to x, y is then post incremented).
    This makes sense to me. However the following code,
    the value of x does not get incremented. Can someone
    explain this to me?
    The following code:
    int x = 0;
    x += x++;
    System.out.println("x = " + x);
    Produces the following output:
    x = 0
    (Value of x is assigned to x, then x does not get post incremented??).

    I code with the mind set of "If the code is not self explanatory or obvious, then
    it's too confusing and should be avoided".
    I am studying for the Java Programmer Certification exam, so this query was more
    to try and understand why the output did not match what I had expected.
    So
    x += x++;
    is the same as (where x' refers to the original value of x)
    x = (x) + (x++);
    which is then executed in the following order:
    x = x++; //(x = x + 1) post incrementation
    x = x' + x'; //(x = 0 + 0) evalutation of the assignment
    Thanks for all the responses!!

  • Post increment problem. please help to solve it

    public class test {
    public static void main(String args[])
         int i=10;
         i=i++;
         System.out.println(i); // value of i is 10 why
    }

    Mostafa.Hashem wrote:
    Absofuckinglutely NOT !
    1) Save current value of x. That is, 1. This is the value of the expression "x++".
    2) Increment x. x is now 2. We have now completed x++
    3) Assign value from step 1 into y.i wonder how small point like this takes all that time.
    Mr Jverd,
    the difference between prefix increment and the postfix increment is :
    IN PREFIX INCREMENT THE ASSIGNMENT OF EXPRESSION DONE FIRST THEN THE INCREMENT.
    IN POSTFIX INCREMENT THE INCREMENT DONE BEFORE THE ASSIGNMENT.Wrong.
    ++x and x++ are both expressions. They have a value and a side effect.
    In pre-increment (++x) the increment is done before the expression is evaluated. The value of the expression is the new value of x.
    In post-increment (x++) the increment is done after the expression is evaluated. The value of the epxression is the original value of x.
    In both cases
    y = ++x;
    y = x++;
    The right-hand side is evaulated completely before the assignment to y is done. In fact, in ALL java assignment statements, the RHS is evaluated completely before assigning anything to the LHS.
    y = ++x;
    is equivalent to
    x +=1;
    y = x;
    y = x++;
    is equivalent to
    tmp = x;
    x += 1;
    y = tmp;

  • Post increment question

    I was looking at this puzzle question:
    public class Assignment {
    public static void main(String[] a) throws Exception {
    int tricky = 0;
    for (int i = 0; i < 3; i++)
    tricky += tricky++;
    System.out.println(tricky);
    tricky is 0. How come the post increment in this case does nothing?

    I was looking at this puzzle question:
    public class Assignment {
    public static void main(String[] a) throws Exception
    int tricky = 0;
    for (int i = 0; i < 3; i++)
    tricky += tricky++;
    System.out.println(tricky);
    tricky is 0. How come the post increment in this case
    does nothing?
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=753569

  • J-CONTENTS & INCREMENT OPERATOR

    I have 2-questions:-
    1. What are the contents of Core Java & Adv. Java?
    Is swing part of Core Java OR Adv. Java?
    2. Let int a=1;
    after execution of statement a=a+++a+a++; value of a will be 5
    after execution of statement a=++a+a+a++; vaue of a will be 6
    after execution of statement a=a+a+++a++; value of a will be 4
    Please Explaine me the logic behind it.
    Thanks & Regards,
    GAJESH TRIPATHI
    09252708020

    gajesh wrote:
    I have 2-questions:-
    1. What are the contents of Core Java & Adv. Java?
    Is swing part of Core Java OR Adv. Java?Huh? There is no official "core" vs. "advanced" (which is what I assume you mean by "adv"). Swing is part of the core API.
    2. Let int a=1;
    after execution of statement a=a+++a+a++; value of a will be 5
    after execution of statement a=++a+a+a++; vaue of a will be 6
    after execution of statement a=a+a+++a++; value of a will be 4
    Please Explaine me the logic behind it.No. That's ridiculous code. You'll never see that for real.
    Instead just learn about the difference between pre-increment (++x) and post-increment (x++).
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op1.html

  • "Row-based Only" checkbox for a post processing operating

    Hi,
    Is there documentation available on the "Row-based Only" checkbox for the post-processing operator? Any links to more information on this would be appreciated.
    Regards,
    Mazen

    Hi Carsten,
    My question is more on what is the use of the "Row-based only" checkbox that shows up in the properties window for a post-processing operator. How does this checkbox affect the execution of the post-processing transformation?
    Regards,
    Mazen

  • Post fix ++ operator

    class C{
         static int f1(int i) {
          System.out.print(i + ",");
          return 0;
         public static void main (String[] args) {
          int i = 0;
          i = i++ + f1(i);
          System.out.println(i);
    }The above code gives the 1,0 output. Anybody explain how and why?
    Thanks in advance...

    public class Precedence {
         static int f1(int i) {
              System.out.print(i + ",");
              return 0;
         public static void main (String[] args) {
              * This is because of operators precedence.
              * Your code is interpreted for the compiler as code bellow.
              int i = 0;
              i++;
              i = f1(i);
              System.out.println(i);
              * line i = (i++) + f1(i);
              * first executes i++;
              * second f1 is executed and its result asigned to i:
              * i = (i++) --> is not more part of execution
              * i = ... f1(i); is set to i.
              * So as f1 returns 0 i gets again 0 value.
    * If you execute this code you'll see
    * that line a = i++; first sets the value of
    * a to the value that contains i and after increment i.
    * If you first want to increment i and then
    * copy the value to a you should do this:
    * a = ++i;
    public class Precedence {
         public static void main(String [] args) {
              int i = 0, a = 0;
              a = i++;
              System.out.println(a);
              System.out.println(i);
    read http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html for more details.

  • Strange Post-Increment/Assignment Behaviour

    I have a problem understanding the code snippet below :
    public class trythis {
         public static void main(String args[])
              int i = 0;
              i = i++; // ??
              System.out.println(i);
    I thought that the output of this program should be 1, but when I ran the progam it gave the output 0.
    I don't understand the reason. Can anyone help me understand the logic behind this?
    Thanks.

    OK so here is an elaborate explanation:
    This is an assignment:
    i = i++;
    According to the Java Language Specification �15.26.1 the first thing that happens is that the left hand side is evaluated. It clearly evaluates to the variable i. The next thing that happens is that the right hand side (i++) is evaluated. So let's look at that...
    This is a postfix increment expression:
    i++
    According to the Java Language Specification �15.14.1 the following happens: The variable is evaluated (this is i which is 0), 1 is added to the variable value (giving a value of 1) and the result is stored in the variable (making i=1). The value of the whole expression (i++) is the value of the variable before it was incremented. The variable i had the value 0 before it was incremented so the value of the right hand side is 0. Now back to the assignment...
    The right hand side has now evaluated to 0. The value of the right hand side is then stored in the variable denoted by the left hand side (i). So after the assignment i has a value of 0.
    S&oslash;ren

  • Increment operator

    hi
    i have a small code snippet
    int i=10;
    i=i++;
    System.out.println(i);as per my knowledge it should result *11*, but it gives *10*,
    could you please tell me the reason for this why it is so ?
    ashish

    In contrary to C or C++, the meaning of i=i++ is well defined in Java.
    It is better avoided though!
    This i=i++ stuff gets regularly discussed.
    http://forums.sun.com/thread.jspa?threadID=231270&tstart=122941
    http://forums.sun.com/thread.jspa?threadID=441193&tstart=72796

  • X increment

    for(int x = 0 ; x < 10 ; ++x)  // x++    Whats the difference between these two types of increments?  The sop is starting with 0 to 9 both the ways.
                   System.out.println("x = " + x);
              }Edited by: bobz on 11-Dec-2009 16:23

    bobz wrote:
    for(int x = 0 ; x < 10 ; ++x)  // x++
    // Whats the difference between these two types of increments?
    You would notice a difference only if you used the side effect of the operator, which side effect differs between the two forms.
    For example:
    int y = -1;
    for (int x = 0; x < 10; y = ++x)
      // Use y here
    }Then change the above to use y = x++ and notice the difference where y is used in the loop.
    Note that I would never write a loop like above, and rarely ever write code that depends on the side-effect. So in almost all of my practice, I can use the pre-increment operator and post-increment operator interchangeably.

  • Expected "unreachable statement" error but it compiled successfully

    Bellow following code, i expected compile time error something like "unreachable statement i++" on line no. 4 as it is obvious that the line returns 'i' and increments 'i' value due to virtue of post increment operator ++. But i didn't get any type of errors - compile time or runtime error - which i thought would get one and ran successfully printing 0.
    Can anybody explain the reason behind this?
    1. class Target {
    2.     private int i = 0;
    3.     public int addOne() {
    4.          return i++;
    5.     }
    6. }
    7. public class Client {
    8.      public static void main(String[] args) {
    9.          System.out.println(new Target().addOne());
    10.     }
    11.}

    karthikbhuvana wrote:
    Ok fine. That's a good example. But my question is, once the control returns from the method addOne(), how it is possible that variable 'i' gets incremented?
    return i++; is equivalent to the following:
    int tmp = i;
    i = i + 1;
    return tmp;The expression i++ is evaluated completely, and then the value of the i++ expression is returned. Evaluating i++ completely means "remembering" the current value of i as the value of the expression, and then incrementing i.
    That's also why
    int i = 0;
    i = i++; // never do this for real
    System.out.println(i);prints out 0, not 1. The RHS is evaluated before assigning to the LHS. The "post" in "post-increment" doesn't mean "after the rest of the statement is done." I means "increment happens after getting the value of the expression."

Maybe you are looking for