Java Increment and Decrement Operators

Java  Increment and Decrement Operators
Java has a number of arithmetic operators that are similar to what you know from elementary math, but it also has some that are specific only to programming languages. The most common and useful of these are probably the increment and decrement operators. If you've looked at any Java code, you have very likely seen these operators used on counters (often called i or cnt by convention), such as i++.

How the Increment and Decrement Operators Affect Numbers
OperatorSymbolPurposeExampleResult
Increment
++
increment by 1
4++
5
Decrement
--
decrement by 1
4--
3

The interesting and sometimes confusing thing about the increment and decrement operators is that they have two forms – prefix and postfix notation – which act slightly differently. Prefix notation is when the operator ("++" or "--") is in front of the number or variable – for instance, --i or ++cnt. Postfix notation is when the operator ("++" or "--") is placed after the number or variable – for instance, i++ or cnt--.

When used in an expression (equation), prefix notation means the increment or decrement takes place before the number or variable is used. In postfix notation, the original value of the number or variable is used and then the increment or decrement takes place. This is easiest to understand by looking at how it works.

Prefix NotationPostfix Notation
Codea=4
b=++a + 2
a=4
b=a++ + 2
ResultThe increment takes place first resulting in the following values:
a=5
b=7
The addition take place first resulting in the following values:
a=5
b=6


Prefix and postfix notation can be confusing, however, a few things make it easier. In the vast majority of cases, the increment and decrement operators are used on their own or in parenthesis. When the increment and decrement operators are used on their own (as they often are when used as loop counters), the prefix and postfix versions work identically. The same is true when they are used in parenthesis. To avoid confusing yourself or other people reading your code, it's a good idea to use increment and decrement operators in expressions sparingly and with parenthesis whenever possible.


This site needs an editor - click to learn more!


You Should Also Read:
Java for Users

RSS
Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.