2

Let's say I have the following code:

int x = 5;
System.out.println(x++);              // Will print 5
System.out.println("Random code");    // Will write "Random code" 
System.out.print(x):                  // Will write 6

My question is: On what line is x actually incremented? Immediately after the postfix? Or right before when the variable is called next in order?

I have heard about sequence points having something to do with the postfix and prefix operators. This is mainly why I asked.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Robert Tossly
  • 613
  • 1
  • 6
  • 14
  • Well the postfix form first returns the current value of the expression and THEN performs the increment operation on that value. So it'll be incremented on line 5 itself. – Siddhartha Oct 16 '15 at 18:25

3 Answers3

1

The postfix form first returns the current value of the expression and THEN performs the increment operation on that value. So it'll be incremented on line 5 itself.

An example of this is the classic for loop:

for (int i = 0; i<10; i++)
{
  //something
}

We often hear that i++ could be replaced by ++i , because the third conditional statement of the for-loop is evaluated there itself.

So if i = 5, it'd be incremented to 6 on that statement itself and then proceed to the for-loop's body. If postfix behaved such that i only got incremented next time it's accessed, then i would've remained 5 thruout that iteration of the loop which would've been entirely different than doing ++1.

Community
  • 1
  • 1
Siddhartha
  • 4,296
  • 6
  • 44
  • 65
1

When you write that code

x++

That returns x value for you and increment x by 1.

So it incremented on line no 5 itself.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

The value of x will be incremented right after it is printed (in this case). What happens is the comparison/ print/ some other operation is performed on the variable, and then directly after such operation, it gets incremented. The same thing will happen if you have something like int z = 0; if (1 > z++) { system.out.println (z) } , it will print 1.

EDIT: There are no sequence points in java. Read this for more information: sequence point concept in java

Community
  • 1
  • 1
peter
  • 78
  • 9