Java Reference
In-Depth Information
again, you can deduce from the result of (−8) / 3 being −2. You have to add −2 to the result of (−2) * 3 to get
the original value, −8. Lastly (−8) % (−3) results in −2, which is also consistent with the divide operation
applied to the same operands.
The modulus operator has the same precedence as multiplication and division and therefore executes be-
fore any add or subtract operations in the same expression. You could add these statements to the program,
too, if you want to see the modulus operator in action. The following statement outputs the following results:
System.out.println("The number of fruit each is " + numFruitEach
+ " and there are " + remainder + " left over.");
The Increment and Decrement Operators
If you want to increment an integer variable by one, you can use the increment operator instead of using an
assignment. You write the increment operator as two successive plus signs, ++ . For example, if you have an
integer variable count that you've declared as
int count = 10;
you can then write the statement
++count; // Add 1 to count
This statement increases the value of count to 11. 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 doesn't seem to have much of an advantage over
writing the following:
count = count - 1; // Subtract 1 from count
However, a big advantage of the increment and decrement operators is that you can use them in an ex-
pression. 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) {
// Declare and initialize three variables
int numOranges = 5;
int numApples = 10;
int numFruit = 0;
// Increment oranges and calculate the total fruit
numFruit = ++numOranges + numApples;
System.out.println("A totally fruity program");
// Display the result
System.out.println("Value of oranges is " + numOranges);
System.out.println("Total fruit is " + numFruit);
}
Search WWH ::




Custom Search