-1

What is the control flow of post-increment operator?

public class PostIncrement
{
    public static void main(String[] args)
    {

        int a = 0;
        for(int i=0;i< 2 ;i++)
        {
            a =a++;     
        }

        for(int i=0 ;i< 1;i++)
        {
            a++;
        }

        System.out.println("Result2 :"+" "+a);        
    }

}

The results are like 0 and 1

Why is it so?

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
Ullas
  • 837
  • 3
  • 10
  • 14

2 Answers2

0

The postfix operator ++ executes after the statement completes.

The first time you print the value of a it prints zero because nothing has changed. Next, you enter a for loop which executes once, incrementing the value of a. It doesn't actually matter that it is postincrement because there are no other instructions in that statement. The value of a is now 1.

You print out 1.

As an aside, your code doesn't actually work because the inner variable i is hiding the outer variable and so you will get a compiler error for redeclaring i. I assumed you mean a different variable here such as j.

ose
  • 4,065
  • 2
  • 24
  • 40
0

a++ would first use the value of a in that particular statement and then increment it.

for eg.

a=0;
sysout(a++);
sysout(a);

The result would be 0 and 1.

So in your case, if you had written the second for loop as

      for(int i=0 ;i< 1;i++)
         {
              sysout(a++);
         }

it will print 0 and 0 and 1.

Adarsh
  • 3,613
  • 2
  • 21
  • 37