We’re about to kick it up a notch. (Not really, you’ll knock this out) You are smart! You are capable!
Sometimes we get new information and want to update a variable. Let’s say we’re taking care of a plant with some gorgeous leaves. It has 12 leaves on it already, let’s keep track with a variable.
Integer numOfLeaves = 12;
If we wake up the next day and see 3 new leaves, we can update our variable using the +
operator as we learned before.
Integer numOfLeaves = 12; Integer newLeaves = 3; numOfLeaves = numOfLeaves + newLeaves; // numOfLeaves is now 15
Nothing wrong with the code above. If we wanted to shorten the syntax and be a little less redundant - we could with compound operators. Using the +=
compound operator we can rewrite our previous code:
Integer numOfLeaves = 12; Integer newLeaves = 3; numOfLeaves += newLeaves; //this is shorthand for numOfLeaves = numOfLeaves + newLeaves; // Or without using a variable for newLeaves Integer numOfLeaves = 12; numOfLeaves += 3; // numOfLeaves is now 15
You can do this with other operators too, like -=
, *=
, and /=
. The full list is available here.
If we wake up the next day and see that we lost 2 leaves, our code would look like this:
Integer numOfLeaves = 15; Integer lostLeaves = 2; numOfLeaves -= lostLeaves; // numOfLeaves is now 13
We have another trick up our sleeves too. We'll see detailed examples of this in the next course, but sometimes we just want to add or subtract 1
from a variable. Instead of doing what we just learned:
Integer numOfLeaves = 13; numOfLeaves += 1; // numOfLeaves is now 14
We can take advantage of two more operators, ++
and --
, called incremet and decrement operators instead:
Integer numOfLeaves = 14; numOfLeaves++; //shorthand for numOfLeaves = numOfLeaves + 1; // numOfLeaves is now 15 numOfLeaves--; // numOfLeaves is now 14
Much better!