Java Reference
In-Depth Information
Increment and Decrement Operators
Now you know how to declare a variable and enter data into a variable. In this section,
you will learn about two more operators: the increment and decrement operators. These
operators are used frequently by Java programmers and are useful programming tools.
Suppose count is an int variable. The statement:
count = count + 1;
increments the value of count by 1 . To execute this assignment statement, the computer
first evaluates the expression on the right, which is count + 1 . It then assigns this value to
the variable on the left, which is count .
As you will see in later chapters, such statements are frequently used to keep track of how
many times certain things have happened. To expedite the execution of such statements,
Java provides the increment operator, ++ , which increases the value of a variable by 1 ,
and the decrement operator, -- , which decreases the value of a variable by 1 .
Increment and decrement operators each have two forms: pre and post. The syntax of
the increment operator is:
Pre-increment:
++variable
Post-increment:
variable++
The syntax of the decrement operator is:
Pre-decrement:
--variable
Post-decrement:
variable--
Let's look at some examples. The statement:
++count;
or:
count++;
increments the value of count by 1 . Similarly, the statement:
--count;
or:
count--;
decrements the value of count by 1 .
Because increment and decrement operators are built into Java, the value of a variable is quickly
incremented or decremented without having to use the form of an assignment statement.
As you can see from these examples, both the pre- and post-increment operators
increment the value of the variable by 1 . Similarly, the pre- and post-decrement operators
 
Search WWH ::




Custom Search