datatype variable[];ALLOCATION
OR
datatype variable[size];
OR
datatype variable[]= {el_1,el_2 , ... ,el_n}
variableREFERENCING ELEMENTS= new
datatype[size];
variable[item]
The DECLARATION section above shows how to declare that a
variable is
an array. The first way declares only that variable will
be an array the elements of which will be of type datatype.
It declares neither the size nor the contents of the array.
The second way initializes the array to be of length n
with elements el_1,el_2, up to el_n as
its contents.
If you do not initialize an array when you declare it, you
will have to allocate before you use it. The syntax is shown
in the ALLOCATION section above. Here we see the
new
keyword which is used to allocated memory for
the array. Note that if the array is already allocated,
and you reallocate this way, the variable will no longer contain
its old contents.
You can reference elements using the syntax shown above. These references can be used anywhere in a Java statement that a variable name would be used. In particular, to assign to an array element you would use variable[item] = value;
Every array has an associated variable called length
that contains the length of the array. If the array were called
vector
, then you would get the length of the
array with vector.length
.
double dotprod{double vector_1[],double vector_2[]) { if( (vector_1.length==3) && (vector_2.length==3)) { for(double sum = 0, int i=0; i< vector_1.length; i++) { sum+=vector_1[i]*vector_2[i]; } return sum; } else { return Double.NaN; } }This method checks that the length of the two arrays are the same - it returns the IEEE float for Not A Number to signify an error (note that Java has a more elegant method of error handling that will not be discussed in this manual). If the arrays have the same length, it calculates and returns the dot product.
Some code that might use the dotprod method above might look like:
double v1[]; double v2[]={.3,.5.,.2}; v1 = new double[3]; for(int i=0;i<3;i++) { v1[i]=i*i; } double dp=dotprod(v1,v2);
![]() |
6.5 Classes |