Lesson 21: Increment and Decrement Operators

In the last lesson we learned about relational operators and how they can be applied in if statements.  In this lesson, we are going to go over increment and decrement operators and how they can be used in our code.  First, let’s go over the increment operator.   

The increment operator is basically nothing more than a way to add 1 to a variable of our choosing.  The typical use of it is directly after an int variable’s name.  Let’s look at the example below.

In the example above, we can see that the if statement will execute because the boolean isMarried is true.  Then, looking at the if statement, we see that the numInHousehold has the increment operator attached at the end.  Therefore, we know that the increment operator inside of our if statement will be executed and Java will print out 2.  Now that we have an idea of how increment operators work, let’s go over decrement operators.

As you can probably guess, decrement operators do the opposite of increment operators.  Instead of adding to a variable, they subtract by 1.  Look at the example below.

In our example, we can see that the if statement will execute.  This is because the relational operator “not equal” is in the conditional statement.  Consequently, when the code inside of our if statement executes, the java will print out our numOfSnickers as 0.

Both of these coding examples we have gone over are referred to as postfix.  Postfix means that the code executes and then the variable is incremented or decremented by 1.  

However, if we wanted to use it as a prefix (before the code is executed), we would simply place the increment sign ++, or decrement sign -- before the variable name instead of after.

For example, the prefix versions of the examples above would be ++numOfHousehold and --numOfSnickers.  Let’s look at the example below for a better understanding of how prefixes work.

Although it seems a little confusing at first, let’s look at what Java prints.

Instead of printing out  i = 10, it instead tells us that i = 11.  That is because we used the prefix increment operator that skipped ahead and incremented int i.   Afterwards, it then went and multiplied our i value by 2 and printed the results.  

It seem like a lot to remember, but just remember that the operator ++ adds by 1, and the operator -- subtracts by 1.

Also, remember that that prefix increment operators execute before the rest of the code, and that postfix increment operators execute after our other code.

GitHub link.

Leave a Reply

%d bloggers like this: