Sams Teach Yourself C in 21 Days

(singke) #1
Java Language Fundamentals 709

BD4


values the variable will be required to hold. All these types are signed, which means they
can hold negative or positive numbers. Table B4.2 provides the details on the integer data
types.

Note that the size of each of the primitive types is the same on all plat-
forms. This is different from C and C++, where the size of the data types
may vary between platforms.

Note


TABLEB4.2 Java’s primitive integer data types
Integer Size Range of values
data type
byte 1 byte (8 bits) –128 to 127
short 2 bytes (16 bits) –32,768 to 32,767
int 4 bytes (32 bits) –2,147,483,688 to 2,147,483,647
long 8 bytes (64 bits) –9.22× 1018 to 9.22× 1018 (approximate range)

Floating Point Numeric Data
For floating point numbers—numbers with a fractional part—Java offers two primitive
types. Type doubleis the one you should use in most circumstances. It takes 8 bytes of
memory, and permits an accuracy of 14 to 15 decimal places, while permitting a huge
range of –1.7× 10308 to 1.7× 10308 , more than enough for any imaginable need.
The second floating point type,float, is provided primarily for compatibility with the
many existing data files that use this format. Type floatis stored in 4 bytes of memory
and is significantly less flexible than type double, offering accuracy of only 6–7 decimal
places and a range of –3.4× 1038 to 3.4× 1038.

Character Data
Java has a single primitive data type called charused to store printable characters. It is 2
bytes in size and is intended to hold the unsigned values 0 to 65,535 that represent the
Unicode character set. Although, technically, a type charholds a numeric value, you
should never use it for numbers.

DO: Use the primitive numerical data
type appropriate for the range of values
your data will have to hold.

DON’T: Use type floatin your programs
unless you need it for compatibility with
existing data files.

DO DON’T


39 448201x-Bonus4 8/13/02 11:19 AM Page 709

Free download pdf