One of the most common operations in
programming is adding or subtracting 1 from a variable. Adding 1
to a variable is called incrementing the variable. Subtracting 1 is called
decrementing. In java, this type of calculation
can be done using ( ++ ) for increment and ( -- ) for decrement. They all belongs to the java math package.
Example)
a++;
We will add 1 to the variable a.
Example)
a--;
We will subtract 1 from the variable a.
Java Using Compound Assignment Operators
A
compound assignment
operator is an operator that performs a calculation and an assignment at the
same time.
| Operator | Description |
| += | Addition and assignment |
| -= | Subtraction and assignment |
| *= | Multiplication and assignment |
| /= | division and assignment |
| %= | Remainder and assignment |
Examples)
1) a += 10; is equivalent to a = a + 10;
2) a *= 2; is equivalent to a = a * 2;
3) a %= 3; is equivalent to a = a % 3;
Java Using the Math Class
Luckily, we do not have to import
anything for the math class. The math class is contained in the java.lang
package.
Therefore, it's automatically available for us to use it. We have two constant
that is already defined in the math class
and ready for us to use it, they are as follow.
| PI | 3.14592653589793 |
| E | 2.718281828459045 |
In addition to that, there are methods such as sqrt() which helps us to do
the square root, pow() which returns
a power, and so on. We will see some examples on how to use the methods later
on.
Java Creating Random Numbers
To create a random number, we would need to import java.util.Random;
Here are the steps that we need to take to generate a random number.
1) import java.util.Random;
2) Random rnumber = new Random();
3) int rn = rnumber.nextInt();
So once we have the random class imported, we can access the random class by
doing step ( 2 ). We can use any name we want.
If we don't like to use rnumber, we can switch to something else. In step ( 3 ),
rn will hold a random number generate from 0 and 1.
Now lets see some programming examples
Example)
ClickHere to download SqrPow.java
Example)
ClickHere to download Dice.java
Example)
ClickHere to download In_de.java