Java Reference
In-Depth Information
TABLE 2 . 1 :
Java primitive types.
(
Type
)
(
Size
)
(
Values
)
1 byte
-128 to 127
byte
short
2 bytes
-32,768 to 32,767
int
4 bytes
-2,147,483,648 to 2,147,483,647
long
8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
10
96
to 10
96
4 bytes
ā
float
10
384
to 10
384
8 bytes
ā
double
1bit
true
of
false
boolean
2 bytes
0 to 65,535
char
letter. For example, the following code declares, sets, and prints the value of an integer
variable.
int
i;
i=3;
System. out . println ( i ) ;
The first line declares the variable
i
to be of type integer. The second line assigns the
number 3 to the variable. The third line prints the value of the variable. The first two lines
can be combined as follows.
int
i=3;
Note that several variables can be declared on the same line. For example, the following
is a valid statement.
int
i=3, j =4;
However, we can define multiple variables in a single line only when all the variables are
of same type.
Note that a computer is not all powerful, that is, it cannot represent an arbitrary number.
For example, we all know that there are infinitely many real numbers, while the main
memory of a computer is finite. This is why Java defines
primitive variable types
that take
a fixed amount of memory. For example, the
byte
type can be used to store a small integer,
while the
long
type can be used to store up to a 19-digit integer. Most of the time, we want
to store an integer that is not very big (less than 10 digits) and we will use the type
int
.
Note that most types allow for both negative and positive integers to be stored. Usually,
the first bit of the binary representation of a number indicates if the number is positive or
negative.
There is a special syntax that is needed in Java to represent a long number. The letter
āLā must be appended to the end of the number. For example, a variable of a
long
type
canbedefinedasfollows.
long
ssn = 999333222L;
A
float
and a
double
must have a decimal point. For example, the number 3 is perceived
as an
int
, while the number 3.0 is considered a
double
.A
float
must also have the letter
F
after it. Here is an example of declaring a variable of type
float
.
float
pi = 3.1415F;
A
byte
is a number that is represented by a single byte (8 bits). A hexadecimal number
can be specified by using the 0x prefix. For example, consider the following code snippet.
byte
x=0x2F;
System. out . println (x) ;