Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

56 HOUR 5:Storing and Changing Information in a Program


An addition expression in Java uses the +operator, as in these statements:
doubleweight = 205;
weight = weight + 10;

The second statement uses the +operator to set the weightvariable equal
to its current value plus 10. Asubtraction expression uses the -operator:
weight = weight - 15;

This expression sets the weightvariable equal to its current value minus 15.
A divisionexpression uses the /sign:
weight = weight / 3;

This sets the weightvariable to its current value divided by 3.
To find a remainder from a division expression, use the%operator (also
called the modulo operator). The following statement finds the remainder
of 245 divided by 3:
int remainder = 245 % 3;

A multiplicationexpression uses the *sign. Here’s a statement that employs
a multiplication expression as part of a more complicated statement:
int total = 500 + (score * 12);

The score * 12part of the expression multiplies scoreby 12. The full
statement multiples scoreby 12 and adds 500 to the result. If scoreequals
20, the result is that totalequals 740: 500 + (20 * 12).

Incrementing and Decrementing a Variable
A common task in programs is changing the value of a variable by one.
You can increase the value by one, which is called incrementingthe vari-
able, or decrease the value by one, which is decrementingthe variable.
There are operators to accomplish both of these tasks.
To increment the value of a variable by one, use the ++operator, as in the
following statement:
x++;

This statement adds one to the value stored in the xvariable.
To decrementthe value of a variable by one, use the --operator:
y--;
Free download pdf