A simple Question with the tricky answer

Discussions

General J2EE: A simple Question with the tricky answer

  1. A simple Question with the tricky answer (4 messages)

    class TestJ
    {
    public static void main(String[] args)
      {
    int i = 0;
    i = i++;
    System.out.println(i);
    i = ++i;
    System.out.println(i);

      }
    }
    It produce output 0 and 1.
    Any logical reason for that?
    Please Reply Soon
  2. class TestJ{public static void main(String[] args)  { int i = 0; i = i++; System.out.println(i); i = ++i; System.out.println(i);  }}It produce output 0 and 1.Any logical reason for that?Please Reply Soon

    i = i++

    The ++ operand AFTER a variable will increment its value AFTER the variable is evaluated. So these are the steps:

    1 - The right hand operand is evaluated. It is evaluated to 0
    2 - "i" is incremented by 1, becoming 1
    3 - The result of the expression (0 - zero) is then assigned back to i, wich returns to its original value 0

    i = ++i

    The ++ operand BEFORE a variable will increment its value BEFORE the variable is evaluated. So these are the steps:

    1 - The right "i" variable is Incremented, becoming 1.
    2 - The right hand operand is evaluated to 1 (the actual value of i)
    3 - The value 1 is assigned back to i
  3. i = i++The ++ operand AFTER a variable will increment its value AFTER the variable is evaluated. So these are the steps:1 - The right hand operand is evaluated. It is evaluated to 02 - "i" is incremented by 1, becoming 13 - The result of the expression (0 - zero) is then assigned back to i, wich returns to its original value 0i = ++iThe ++ operand BEFORE a variable will increment its value BEFORE the variable is evaluated. So these are the steps:1 - The right "i" variable is Incremented, becoming 1.2 - The right hand operand is evaluated to 1 (the actual value of i)3 - The value 1 is assigned back to i
    If i is 0 then it assigns and next again it becomes 0 hows that could be possible. first it assigns then increments this is how it performs.
  4. Why is this post in the J2EE General Forum?????
  5. This sorta mimics what happens:

    class I {
    private int value;

    public static void main(String[] args){
    I i = new I();
    i.assign(i.postIncrement());
    System.out.println(i);
    i.assign(i.preIncrement());
    System.out.println(i);
    }

    public int postIncrement(){
    int ret;
    ret = value;
    value++;
    return ret;
    }

    public int preIncrement(){
    int ret;
    value=value+1;
    ret = value;
    return ret;
    }

    public int assign(int value){
    this.value = value;
    return this.value;
    }

    public String toString(){
    return ""+value;
    }
    }

    Couldn't remember enough assembler to translate your code exactly.

    i = i++; <=> do nothing sorta, either use:
    i++;
    or
    i = i+1;