Number types
And
some problems
How numbers are stored
In Java, every value is either an object or a
primitive type
An object name
is really a reference variable
Some languages call reference variables pointers
They are really addresses of bytes in RAM
A primitive name actually stores the value
itself
Numbers in the computer
Primitive types
Four integers type
byte -- 8 bit signed integral value
short -- 16-bit signed
int-- 32 bit signed (most commonly used)
long -- 64 bits
Floats
float 32 bits (6 to 7 significant decimal digits ,
exponent to 38)
double 64 bits (15 significant decimal digits, exponent to 308)
How floats are stored
As we have said, integers are stored in the binary
number system
Floating point numbers must keep track of the decimal
point, so they cannot be stored the same as integers
The decimal point
is moved to the first digit of the number, and the number of places it is moved
is the exponent
The exponent can be either positive or negative
So for a float, you have to keep track of two things
The digits in the
number (called the mantissa)
The exponent (the
placement of the decimal)
This makes
floating point calculations quite slow
Casting
Since integers and floats are stored differently in
the computer, they are not interchangeable
If you try to use
an integer as a float, the compiler does an automatic cast.
This means it
takes the integer, moves the decimal point to the front, then
stores the exponent and mantissa.
But if you try to use a float as an integer,
the compiler complains, since data might be lost.
If you dont mind losing the fractional part of the
number, you can force the compiler to cast a float into an integer
It just truncates
the fractional part of the number
Syntax for casting
Anytime you use an integer and a double together in an
expression, the compiler will automatically cast the integer to a double
Example:
int
num1, num2;
double
dub1, dub2;
dub2
= num1 + dub1;
num2 = num1 + dub1;
// error message
num2 = num1 + (int)dub1;
// this will work; it truncates dub1
Formatting floats with printf
printf(%f) lets you specify two things
The width of the field
If you dont specify the field width, it will just
automatically be whatever size needed
The number of digits after the decimal point (called
the precision)
If you dont specify the precision, it will print out
whatever is needed, max about 14 decimal places
Syntax
System.out.printf("dub2
is %.2f\n", dub2);
Problems with numbers
Rounding errors with floats or doubles
Floating point
numbers can often not be expressed exactly
Example: 1/3 or pi
The problem is
worse in binary than in decimal
See how the compiler handles 4.35
*100
Overflow with ints
If you try to
store a number that is larger than the number of bits necessary
, the results are wrong
See how the compiler handles 1000000*1000000