Java Reference
In-Depth Information
NOTE The Java compiler assumes that your source code is in the default character encoding
for the environment in which you are working. If it is not, you must specify the -encoding
option to tell the compiler about the character encoding for you source code. For example, if
you have created the source file Test.java in Unicode, you can compile it with the following
command:
javac.exe -encoding unicode JavaTest.java
Variables and Types
As I mentioned earlier, each variable that you declare can store values only of a type consistent with the
data type of that variable. You specify the type of a particular variable by using a type name in the variable
declaration. For instance, here's a statement that declares a variable that can store integers:
int numberOfCats;
The data type in this case is int and the variable name is numberOfCats . The semicolon marks the end of
the statement. The variable, numberOfCats , can only store values of type int . Of course, int is a keyword.
Many of your variables will be used to reference objects, but let's leave those on one side for the moment
as they have some special properties. The only things in Java that are not objects are variables that corres-
pond to one of eight basic data types, defined within the language. These fundamental types are referred to
as primitive types , and they enable you to define variables for storing data that fall into one of three categor-
ies:
• Numeric values, which can be either integer or floating-point
• A single Unicode character
• Logical values that can be true or false
All of the type names for the basic variable types are keywords in Java so you must not use them for
other purposes. Let's take a closer look at each of the primitive data types and get a feel for how you can use
them.
INTEGER DATA TYPES
There are four types of variables that you can use to store integer data. All of these are signed — that is,
they can store both negative and positive values. The four integer types differ in the range of values they can
store, so the choice of type for a variable depends on the range of data values you are likely to need.
The four integer types in Java are shown in Table 2-1 :
TABLE 2-1 : Java Integer Types
DATA
TYPE
DESCRIPTION
Variables of this type can have values from −128 to +127 and occupy 1 byte (8 bits) in memory
byte
 
 
Search WWH ::




Custom Search