Java Reference
In-Depth Information
int value = -2147483648 - 1 ;
// value will actually be 2147483647
Java does not report warnings or errors on overflow, so be careful when working with num-
bers close to the maximum or minimum range of a given type.
When a floating-point number is too small (i.e., too close to zero) to be stored, it causes
underflow . Java approximates it to zero, so normally you don't need to be concerned about
underflow.
what is underflow?
Common Error 3: Round-off Errors
A round-off error , also called a rounding error , is the difference between the calculated
approximation of a number and its exact mathematical value. For example, 1/3 is approxi-
mately 0.333 if you keep three decimal places, and is 0.3333333 if you keep seven decimal
places. Since the number of digits that can be stored in a variable is limited, round-off errors
are inevitable. Calculations involving floating-point numbers are approximated because these
numbers are not stored with complete accuracy. For example,
floating-point approximation
System.out.println( 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 );
displays 0.5000000000000001 , not 0.5 , and
System.out.println( 1.0 - 0.9 );
displays 0.09999999999999998 , not 0.1 . Integers are stored precisely. Therefore, calcula-
tions with integers yield a precise integer result.
Common Error 4: Unintended Integer Division
Java uses the same divide operator, namely / , to perform both integer and floating-point
division. When two operands are integers, the / operator performs an integer division. The
result of the operation is an integer. The fractional part is truncated. To force two integers to
perform a floating-point division, make one of the integers into a floating-point number. For
example, the code in (a) displays that average is 1 and the code in (b) displays that average
is 1.5 .
int number1 = 1 ;
int number2 = 2 ;
double average = (number1 + number2) / 2 ;
System.out.println(average);
int number1 = 1 ;
int number2 = 2 ;
double average = (number1 + number2) / 2.0 ;
System.out.println(average);
(a)
(b)
Common Pitfall 1: Redundant Input Objects
New programmers often write the code to create multiple input objects for each input. For
example, the following code reads an integer and a double value.
Scanner input = new Scanner(System.in);
System.out.print( "Enter an integer: " );
int v1 = input.nextInt();
Scanner input1 = new Scanner(System.in);
System.out.print( "Enter a double value: " );
double v2 = input1.nextDouble();
BAD CODE
 
 
Search WWH ::




Custom Search