Java Reference
In-Depth Information
Integer Division and Remainders
When you divide one integer by another and the result is not exact, any remainder is discarded, so the
final result is always an integer. The division 3/2, for example, produces the result 1, and 11/3 produces
the result 3. This makes it easy to divide a given quantity equally amongst a given number of recipients.
To divide numFruit equally between four children, you could write:
int numFruitEach = 0; // Number of fruit for each child
numFruitEach = numFruit/4;
Of course, there are circumstances where you may want the remainder and on these occasions you can
calculate the remainder using the modulus operator, % . If you wanted to know how many fruit were left
after dividing the total by 4, you could write:
int remainder = 0;
remainder = numFruit % 4; // Calculate the remainder after division by 4
You could add this to the program too if you want to see the modulus operator in action. The modulus
operator has the same precedence as multiplication and division, and is therefore executed in a more
complex expression before any add or subtract operations.
The Increment and Decrement Operators
If you want to increment an integer variable by one, instead of using an assignment you can use the
increment operator, which is written as two successive plus signs, ++ . For example, if you have an
integer variable count declared as:
int count = 10;
you can then write the statement:
++count; // Add 1 to count
which will increase the value of count to 11. If you want to decrease the value of count by 1 you can
use the decrement operator, -- :
--count; // Subtract 1 from count
At first sight, apart from reducing the typing a little, this does not seem to have much of an advantage
over writing:
count = count - 1; // Subtract 1 from count
One big advantage of the increment and decrement operators is that you can use them in an expression.
Try changing the arithmetic statement calculating the sum of numApples and numOranges in the
previous example:
public class Fruit {
public static void main(String[] args) {
Search WWH ::




Custom Search