# The increment and the decrement operators

• The Assignment Operator - Revisited

• Some students may be confused about the use of =

• The symbol = in Java denotes the assignment operation

• Assignment is not the same as mathematical equality

• Example:

 ``` public class Increment { public static void main(String[] args) { int items = 10; System.out.print("items = "); System.out.println(items); items = items + 1; // Assignment System.out.print("items = "); System.out.println(items); } } ```

• Mathematically speaking, items = items + 1 is "FALSE" (items is NOT equals to (items + 1))

• In Java, the expression "items = items + 1" means:

• Compute the value of the expression on the RIGHT Hand Size of the = operator.
• Assign (store) this value into the variable on the LEFT Hand Size of the = operator.

• The following diagram shows what is going on in the statement items = items + 1:

• Thus, statement "items = items + 1;" will increase the value in the variable items by 1...

• DEMO Program: (Demo above code)

• The Increment operator ++

• Adding 1 to a variable is a very commonly used operation in computer programming (if you have written enough programs, you can testify to the validity of this statement)

• It is so common that some programming languages have defined an computer operation for adding 1 to a variable.

• In Java (and many other programming languages, e.g., C++), this operator is denote as:

 ``` ++ ```

(2 consecutive +'s without an space between them !!!)

• So we can rewrite the above program using this increment operation to add 1 to the variable items as follows:

 ``` public class Increment { public static void main(String[] args) { int items = 10; System.out.print("items = "); System.out.println(items); items++; // Add 1 to variable items System.out.print("items = "); System.out.println(items); } } ```

• DEMO Program: (Demo above code)

Change the assignment to an increment operation !

• The Decrement operator --

• Subtract 1 from a variable is ALSO a very commonly used operation in computer programming

• Needless to say that Java also has defined an computer operation for subtracting 1 from a variable.

• In Java (and many other programming languages, e.g., C++), this operator is denote as:

 ``` -- ```

(2 consecutive -'s without an space between them !!!)

• We can use decrement operation to subtract 1 from the variable items as follows:

 ``` public class Decrement { public static void main(String[] args) { int items = 10; System.out.print("items = "); System.out.println(items); items--; // Subtract 1 from variable items System.out.print("items = "); System.out.println(items); } } ```

• DEMO Program: (Demo above code)