Java Reference
In-Depth Information
// 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);
}
}
The lines that have been altered or added have been highlighted. In addition to the change to the
numFruit calculation, an extra statement has been added to output the final value of numOranges .
The value of numOranges will be increased to 6 before the value of numApples is added, so the value
of fruit will be 16. You could try the decrement operation in the example as well.
A further property of the increment and decrement operators is that they work differently in an
expression depending on whether you put the operator in front of the variable, or following it. When
you put the operator in front of a variable, as in the example we have just seen, it's called the prefix
form. The converse case, with the operator following the variable, is called the postfix form. If you
change the statement in the example to:
numFruit = numOranges++ + numApples;
and run it again, you will find that numOranges still ends up with the value 6, but the total stored in
numFruit has remained 15. This is because the effect of the postfix increment operator is to change the
value of numOranges to 6 after the original value, 5, has been used in the expression to supply the
value of numFruit . The postfix decrement operator works similarly, and both operators can be applied
to any type of integer variable.
As you see, no parentheses are necessary in the expression numOranges++ + numApples . You could
even write it as numOranges+++numApples and it will still mean the same thing but it is certainly a
lot less obvious what you mean. You could write it as (numOranges++) + numApples if you want to
make it absolutely clear where the ++ operator belongs. It is a good idea to add parentheses to clarify
things when there is some possibility of confusion.
Computation with Shorter Integer Types
All the previous examples have quite deliberately been with variables of type int . Computations with
variables of the shorter integer types introduce some complications. With arithmetic expressions using
variables of type byte or short , all the values of the variables are first converted to type int and the
calculation is carried out in the same way as with type int - using 32-bit arithmetic. The result will therefore
be type int - a 32-bit integer. As a consequence, if you change the types of the variables numOranges ,
numApples , and numFruit in the original version of the program to short , for example:
Search WWH ::




Custom Search