Videos
These are called Pre and Post Increment / Decrement Operators.
x++;
is the same as x = x + 1;
x--;
is the same as x = x - 1;
Putting the operator before the variable ++x; means, first increment x by 1, and then use this new value of x
int x = 0;
int z = ++x; // produce x is 1, z is 1
int x = 0;
int z = x++; // produce x is 1, but z is 0 ,
//z gets the value of x and then x is incremented.
++ and -- are called increment and decrement operators.
They are shortcuts for writing x = x+1 (x+=1) / x = x-1 (x-=1). (assumed that x is a numeric variable)
In rare cases you could worry about the precedence of the incrementation/decrementation and the value the expression returns: Writing ++x it means "increment first, then return", whereas x++ means "return first, then increment". Here we can distinguish between pre- and post increment/decrement operators.
Something to understand:
The post-increment operator (++ after the variable name) returns the old value of the variable and then increments the variable. So, if x is 5, then the expression x++ evaluates to 5 and has the side effect that x is set to 6.
This one is a bit special:
x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46
Note that string concatenation is being used here. It prints Result =, then 4 which is the value of z, then the value of y++ * x which is 6. The 46 is not one number, it is a 4 and a 6 put after each other coming from two expressions.
x = 5; y = 10;
System.out.println(z = y *= x++); // output is 50 -->z=y=y*x i.e, z=y=10*5 (now, after evaluation of the expression, x is incremented to 6)
x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46 --> from Right to left . y++ * x happens first..So, 3 * 2 = 6 (now, y will be incremented to 4) then "Result = " +z (String) + number (y++ * z) will be concatenated as Strings.
x = 5;
System.out.println( x++*x); // output is 30 --> 5 * (5+1 i.e, x is already incremented to 6 when you do x++ so its like 5 *6 )
x = 5;
System.out.println( x*x++); // output is 25 -- > 5 * 5 (x will be incremented now)