Difference between x ++ and ++ x?

Possible duplicate:
Is there a difference between x ++ and ++ x in java?

I am reading the official Java tutorial and I do not understand the difference between postfix and prefix (++ x vs x ++). Can someone explain?

+3
source share
6 answers

++x: increment x; the value of the general expression is the value after the increment

x++: increment x; the value of the general expression is the value before the increment

Consider these two sections:

int x = 0;
System.out.println(x++); // Prints 0
// x is now 1

int y = 0;
System.out.println(++y); // Prints 1
// y is now 1

I personally try to avoid using them as expressions in a larger statement - I prefer stand-alone code, for example:

int x = 0;
System.out.println(x); // Prints 0
x++;
// x is now 1


int y = 0;
y++;
System.out.println(y); // Prints 1
// y is now 1

, , x y, .

, pre/post-increment, , .

+11

++ x x x ++ x,

:

int x = 0;
int A = ++x; // A = 1
int B = x++; // B = 1
int C = x;   // C = 2
+5

++x , x++ - . .

+2

, , ... post-and pre-increment , x + 1, , . :

int x = 5;
x = ++x; 
System.out.println( x ); // prints 6
x = x++; 
System.out.println( x ); // prints 6!
x = ++x + x++; 
System.out.println( x ); // prints 14!

( ...). x = x++ - ... !

+2

, , . , - ++ x x, , x ++ x, .

+1

, ++ x 1 x x, x ++ 1 . , .

x

int x = 3;

System.out.println x, infix:

System.out.println(++x);

x 4, println "4". , :

x+=1;
System.out.println(x);

, x 3. System.out.println x postfix:

System.out.println(x++);

current x, "3" , x. :

System.out.println(x);
x+=1;

, .

+1

Source: https://habr.com/ru/post/1785991/


All Articles