Java Reference
In-Depth Information
Let's take a look at the IntegerDemo program in detail. Assigning x to the
value 250 and displaying it is fairly straightforward. Notice that you can
declare more than one variable at a time, with a, b, and c all being declared
shorts in one statement. An interesting note about Java is that it performs inte-
ger arithmetic at the int level, so b+c returns an int. This means that the sum
must be cast to a short before assigning it the value to a because a is a short.
The variable y is declared as a long and assigned to an integer literal that is
larger than 32 bits. The literal is appended with an L to denote it as a long. This
line of code would not compile if the L were omitted.
When you hard-code a numeric value in your code, that value is referred to
as a literal. For example, in the IntegerDemo program shown in Figure 2.1,
the numbers 250, 21, 9, and 12345678987654321 are integer literals. (They
are integer literals because they do not contain a decimal point.) In Java,
integer literals are treated as int values, which is fine in most situations.
However, when an integer literal is too large to fit into a 32-bit int, the
literal cannot be treated as an int. In these situations, you need to append
the literal with an L to denote that the literal is to be stored as a long, not
an int.
Take special note of the statement y = x, where y is a long and x is an int.
These two variables are different data types, but no cast operator is used. This
is because an int is assured of fitting into a long without any loss of data. When
y is assigned to x, the value of x is simply promoted to a long and stored in y.
However, assigning the byte s to the short c requires the cast operator. The
short c is 16 bits and s is only 8, so there is a possible loss of data. Without the
cast operator, the assignment will not compile.
The output of IntegerDemo is shown in Figure 2.1.
Figure 2.1
Output of the IntegerDemo program.