Java Reference
In-Depth Information
Do I Need to Memorize These Sizes?
Not all of them. Don't try to memorize the range of values in a long , float , or double , but
it is important to know their size in bits. However, you should be able to state the range of
a byte exactly and recognize when a short or int has likely gone beyond its range. Expect a
question involving the size of a char , especially because a char in C/C++ is only 8 bits and
uses the ASCII format, while a Java char is 16 bits and uses the UNICODE format.
Primitive types are allocated in memory by declaring them in your code. For example,
the following lines of code declare an int and a double :
int x;
double d;
In memory, the compiler allocates 32 bits for the variable x and 64 bits for the variable d .
A primitive type can only store a value of that same type. For example, the variable x can
only hold an int and d can only hold a double . Suppose we assign values to x and d :
x = 12345;
d = 2.7e45;
Figure 1.5 shows how these primitive types look in memory. The value 12345 is stored
in the memory where x is allocated. Similarly, the value 2.7e45 is stored in the memory
where d is allocated.
FIGURE 1.5 An int is 32 bits and a double is 64 bits.
x
d
12345
2.7e45
32 bits of memory
64 bits of memory
Reference Types
Reference types are variables that are class types, interface types, and array types.
A reference refers to an object (an instance of a class). Unlike primitive types that hold their
values in the memory where the variable is allocated, references do not hold the value of
the object they refer to. Instead, a reference “points” to an object by storing the memory
address where the object is located, a concept referred to as a pointer . However, the Java
language does not allow a programmer to access a physical memory address in any way, so
even though a reference is similar to a pointer, you can only use a reference to gain access
to the fi elds and methods of the object it refers to. It is impossible to determine the actual
address stored in the memory of the reference variable.
Search WWH ::




Custom Search