= Returns a value
Take a look at the following example:
public class MyProgram {
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = (y = x); //performs (y=x) first, then (z=1)
System.out.println(x); //Prints 1
System.out.println(y); //Also prints 1
System.out.println(z); //Also prints 1
}
}
With int z = (y = x);
, the (y=x) is executed first, storing 1 into y. However, (y=x) also evaluates to the expression 1 of type int. Thus, the rest of the statement becomes int z = 1;
Incrementing
We often want to add a variable by a value, and store the new value into the variable. For example, if we want to increase x by 1, we would perform x = x + 1
. Like any assignment, the right side is evaluated first, and it is then stored into the left side.
public class MyProgram {
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = (y = x); //performs (y=x) first, then (z=1)
x = x + 2; //Now x is 1+2, or 3
y = y * 5; //Now y is 1*5, or 5
z = z - 3; //Now z is 1-3, or -2
System.out.println(x);
System.out.println(y);
System.out.println(z);
y = y / 2; //Now y is 5/2 or 2
x = x % 2; //Now x is 3%2 or 1
System.out.println(x);
System.out.println(y);
}
}
+=, -=, *=, /=, and %=
The +=, -=, *=, /=, and %= operators are sometimes called convenience operators, because they only exist to make your life easier. x += 42 is the same as x = x + 42. y *= 5 is the same as y = y * 5:
public class MyProgram {
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = (y = x);
x = x + 2;
y *= 5; //Now y is 1*5, or 5
z -= 3; //Now z is 1-3, or -2
System.out.println(x);
System.out.println(y);
System.out.println(z);
y /= 2; //Now y is 5/2 or 2
x %= 2; //Now x is 3%2 or 1
System.out.println(x);
System.out.println(y);
}
}
Prefix Increment and Decrement
In many programs, you want to increase a value by just 1. Since this is so common, the ++ and -- operators was created to make +=1 and -=1 easier to type:
public class MyProgram {
public static void main(String[] args) {
int x = 41;
System.out.println(x); //41
++x;
System.out.println(x); //42
System.out.println(x+=1); //43
System.out.println(++x); //44
--x;
System.out.println(x); //43
System.out.println(--x); //42
}
}
Postfix Increment and Decrement
You can also type x++ instead of ++x. These two expressions both add one to x, but they are different when used in a expression such as y = (++x) vs y = (x++).
Advanced programmers should recognize that postfix returns the value *before* increment. For example int x=1,y=x++;
has y equal to 1 and x equal to 2. In contrast, int x=1,y=++x;
has both variables equal to 2. If this confuses you, avoid using increment and decrement operators as part of an expression.