PT - Compound Assignment Operators (Lesson)
Compound Assignment Operators
Introduction
We live in a fast-paced world that is always trying to find the shortcut. We want mundane things shorter, easier, faster, more efficient. The same can be true about coding. Why type a whole statement if you can shorten it? You might think that the Java syntax we have learned so far is short enough, but it doesn’t stop there! There are even more compound ways to write statements dealing with mathematical expressions.
Compound assignment operators can be used to both evaluate an expression and assign a value to a variable. Click each compound operator in the activity below to reveal an example and meaning.
Increment/Decrement Operators
To increment and decrement a variable we can use the ++ or –- symbols.
++ adds 1 to any integer or double
-- subtracts 1 from any integer or double
x++ is the same as x = x + 1;
x-- is the same as x = x – 1 ;
Compound Operators Practice
Click in the box below to begin the Compound Operators Practice Activity.
++num VS num++
The placement of the increment or decrement operators makes a difference in the code.
When the increment is before the variable, increase it by one then complete the statement. When the increment comes after, complete the assignment first, and then increase the variable by 1. The same is true with decrement.
IMAGES CREATED BY GAVS