Java Reference
In-Depth Information
Data Types
The objective of a Java program is to manipulate data. Different programs manipulate
different data. A program designed to calculate an employee's paycheck will add, subtract,
multiply, and divide numbers; some of the numbers might represent hours worked and
pay rate. Similarly, a program designed to alphabetize a class list will manipulate names.
You wouldn't expect a cherry pie recipe to help you bake cookies. Similarly, you
wouldn't manipulate alphabetic characters with a program designed to perform arithmetic
calculations. Furthermore, you wouldn't multiply or subtract names. Reflecting such
underlying differences, Java categorizes data into different types, and only certain opera-
tions can be performed on a particular type of data. At first, it may seem confusing, but by
being so type conscious, Java has built-in checks to guard against errors.
Data type: A set of values together with a set of operations on those values.
Primitive Data Types
The primitive data types are the fundamental data types in Java. There are three categories
of primitive data types:
￿ Integral, which is a data type that deals with integers, or numbers
without a decimal part (and characters)
￿ Floating-point, which is a data type that deals with decimal numbers
￿ Boolean, which is a data type that deals with logical values
Integral data types are further classified into five categories: char , byte , short , int , and
long .
Why are there so many categories of integral data types? Every data type has a different set
of values associated with it. For example, the int data type is used to represent integers
between 2147483648 ( ¼ 2 32 ) and 2147483647 ( ¼ 2 32 1). The data type short is
used to represent integers between 32768 ( ¼ 2 15 ) and 32767 ( ¼ 2 15 1).
Which data type you use depends on how big a number your program needs to deal with.
In the early days of programming, computers and main memory were very expensive.
Only a small amount of memory was available to execute programs and manipulate data.
As a result, programmers had to optimize the use of memory. Because writing a program
and making it work is already a complicated process, not having to worry about the size
of the memory makes for one less thing to think about. To effectively use memory, a
programmer can look at the type of data used in a program and figure out which data type
to use. (Memory constraints may still be a concern for programs written for applications
such as a wrist watch.)
Table 2-2 gives the range of possible values associated with the five integral data types and
the size of memory allocated to manipulate these values.
 
 
 
Search WWH ::




Custom Search