Java Reference
In-Depth Information
Because x is a short, x consumes 16 bits of memory and can contain any inte-
ger value between -32768 and 32767 (refer to Table 2.2). Similarly, age is an int
and consumes 32 bits of memory, whereas salary is a float and also consumes
32 bits of memory.
The variables age and salary consume the same amount of memory:
32 bits. However, they are quite different in the way they can be used. The
variable age can store only integer numbers, those without a decimal value.
Because salary is a float, it stores numbers with decimals, using the IEEE
754 standard for floating-point values. This allows salary to store much
larger values than age , with some loss of accuracy in large values.
Assigning Variables
The term variable is used because the data stored in a variable can vary. In
other words, you can change the value of a variable. In Java, you use the
assignment operator = to assign a variable to a particular value.
For example, the following statements declare an integer x and assign it the
value 12.
int x;
x = 12;
Note that a variable can assign a value at the time it is declared. The previous
two statements could have been replaced with the following single statement:
int x = 12;
Java is strict about letting you assign variables only to values that match the
variable's data type. If x is an int, you cannot assign it to other data types
unless you use the cast operator.
For example, the following statements declare x as an int and then attempt
to assign x to a floating-point value.
int x;
double d = 3.5;
x = d; //This does not compile!
x = (int) d; //This does compile since I used the cast operator.
Search WWH ::




Custom Search