2.5. Arithmetic Calculations

You store the result of a calculation in a variable by using an assignment statement. An assignment statement consists of three elements: the name of the variable where you want the result stored; the assignment operator, =, which indicates that this is indeed an assignment operation; and an arithmetic expression that defines the calculation you want to perform. The whole thing is terminated by a semicolon that marks the end of the assignment statement. Here's a simple example of an assignment statement:

numFruit = numApples + numOranges;       // Calculate the total fruit

When this statement executes, the value of the expression to the right of the assignment operator, =, is calculated, and the result is stored in the variable that appears to the left of the = sign. In this case, the values stored in the variables numApples and numOranges are added together, and the result is stored in the variable numFruit. Of course, you would have to declare all three variables before this statement.

Incrementing a variable by a given amount is a common requirement in programming. Look at the following assignment statement:

numApples = numApples + 1;

The result of evaluating the expression on the right of the = is one more than the value of numApples. This result is stored back in the variable numApples, so the overall effect of executing the statement is to increment the value in numApples by 1. You will see an alternative, more concise, way of producing the same effect ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.