Java Reference
In-Depth Information
The type long for operations with 64-bit values where the value has an L appended
The type int for operations with 32-bit values for all other cases where there is no L at the
end of the number
Errors in Integer Arithmetic
If you divide an integer value by zero, no sensible result can be produced so an exception will be
thrown. An exception is the way of signaling errors in Java that we will discuss in detail in Chapter 7.
Using the % operator with a variable or expression for the right hand operand that has a zero value will
also cause an exception to be thrown.
Note that if an integer expression results in a value that is outside the range of the type of the result, the
result will be truncated to the number of bits for the type you are using and therefore will be incorrect,
but this will not be indicated in any way. It is up to you to make sure that the integer types that you are
using in your program are always able to accommodate any value that might be produced by your
calculations. Problems can arise with intermediate results in some situations. Even when the ultimate
result of an expression is within the legal range, if any intermediate calculation is outside the range it
will be truncated causing an incorrect result to be produced. To take a trivial example - if you multiply
1000000 by 2000000 and divide by 500000 using type int , you will not obtain the correct result if the
multiplication is executed first, because the result of the multiplication exceeds the maximum that can
be stored as type int . Obviously where you know this sort of problem can occur, you may be able to
circumvent it by using parentheses to make sure the division takes place first - but you need to
remember that integer division produces an integer result, so a different sequence of execution can
produce a different answer.
Floating Point Calculations
The four basic arithmetic operators, + , - , * , / , are also available for use in floating point expressions.
We can try some of these out in another version of the Fruit program which we'll call
AverageFruit .
Try It Out - Average Fruit
Make the following changes to the Fruit.java file, and save this as AverageFruit.java . If
necessary, you can add in the code we used earlier to make the program wait for the Enter key to be
pressed before finishing.
public class AverageFruit {
public static void main(String[] args) {
// Declare and initialize three variables
double numOranges = 50.0E-1; // Initial value is 5.0
double numApples = 1.0E1; // Initial value is 10.0
double averageFruit = 0.0;
averageFruit = (numOranges + numApples) / 2.0;
System.out.println("A totally fruity program");
System.out.println("Average fruit is " + averageFruit);
}
}
Search WWH ::




Custom Search