PT - Compound Assignment Operators (Lesson)

APCompSci_LessonTopBanner.png

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 ;

 

int num = 5;
num+;    // now num is 6 

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.

int num = 5;
num++;// now num is 6

count = ++num;
//This increments num first,
//then stores the value in count...
//num is 7 and count is 7.

count = num++;
//This stores num in count first,
//then increases num count.
//count is 7 and num is 8 

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. 

APCompSci_LessonBottomBanner.png

IMAGES CREATED BY GAVS