Java Reference
In-Depth Information
address: 1000
a = 1000
2468 0
FIGURE 5.1: Example array.
the identifier of the object. Note that the 64-bit Java Virtual Machine can support more
than 2 32 objects. However, printing the result of the operator new always results in a 32-bit
number. Therefore, it is possible that the same value is printed for two distinct objects. We
believe that this is an implementation detail and should not affect the way we write our
code.
The operator new returns a unique object identifier or a reference to an object.
When we try to print this value, a function of this identifier is printed. Although
this identifier is different from the address of the object, we will consider it to be the
address of the object. This assumption will in no way affect our code. However, it will
help us better understand how to work with object references.
So far, we have declared variables that belong to primitive types (e.g., int , double , char ,
etc.). Next, we are going to declare a variable that has type that is an array of integers.
Such a variable can be declared as follows.
int [] a;
Note that it is also legal for the square brackets to appear after the variable. In other
words, the above statement is equivalent to the following statement.
int a[];
The first statement can be read as “the variable a is of type array of integers”. This syn-
tax seems more intuitive and will be used throughout the textbook. The second syntax is
supported mainly for historical reasons (e.g., in the C language an array is declared as: int
a[10] ). Note that, also for historical reasons, a , b , c ,and d are common names for arrays. Of
course, the name of an array should be less generic and more descriptive whenever possible.
The declaration of an array and its memory allocation can be combined in a single
statement.
int [] a = new i n t [100];
This will allocate memory for one hundred integers. Remember that an array is just a
sequence of variables of the same type that are allocated simultaneously. The elements of
an array of 100 elements are: a[0] , a[1] , ... , a[99] . Note that the counting always starts
at 0 and goes up to the length of the array minus one (this is analogous to the British
system for counting floors). If you try to access the element at position 100, you will get an
ArrayIndexOutOfBoundsException . The reason is that the element at position 100 is not
part of the array.
Figure 5.1 shows an example array. In the figure, we assume that the array is allocated
at address 1000. Since the size of an integer in Java is four bytes, the array will take 4*5 =
20 bytes. The code to create the array can be written as follows.
int [] a = new i n t [5];
a[0] = 2;
a[1] = 4;
a[2] = 6;
 
Search WWH ::




Custom Search