+ 2
what is the difference between ++x and x++?
6 Answers
+ 3
++x - First increment then give the value
x++ - first give the value then increment
int x = 1;
int y = 1;
System.out.println(++x); // output 2
System.out.println(y++); // output 1
+ 3
++x is pre-incrementation and x++ is post-incrementation.
for example:
int x=2, y=2, z1, z2;
z1=++x; //line 1
z2=y++; //line 2
what do you think what should be the values of z1, z2 and x, y;
z1 = 3, z2= 2;
and x=y=3;
why is this so because while execution of line 1, x is pre-incremented before assignment and in line 2 the value of y is assigned to z2 and then y incremented unlike of line 1.
+ 2
I dont know how it works in java but in js is :
x=3;
y=2;
z= x++ +y; // z=5 x=3
and
x=3;
y=2;
z= ++x +y; // z=6 x=3
0
++X is prefix means it operates first n later changes value of X n X++ is postfix means it changes value later
0
let
a=++x; // case 1
b=y++; // case 2
for e.g let x have initial value of 5 so value of
a is 6, as it is increased by 1 first then assigned to a..
let y=5
but in case 2 value of b is assigned to be 5 first then y is increased by 1.
so at end of the program
x==6
y==6
a==6
b==5
0
++x increments value by 1 prior assigning to new variable
x++ assigns old value to new variable and increments old variable up by 1.