Learning Outcomes:: Arrayrefvar - Length
Learning Outcomes:: Arrayrefvar - Length
ARRAYS
Learning Outcomes:
■ To describe why arrays are necessary in programming.
■ To declare array reference variables and create arrays.
■ To obtain array size using arrayRefVar.length and know default values
in an array.
■ To access array elements using indexed variables.
■ To declare, create, and initialize an array using an array initializer.
■ To program common array operations (displaying arrays, summing all
elements, finding the minimum and maximum elements, random shuffling,
and shifting elements).
■ To simplify programming using the for-each loops.
Introduction to Array
A single array variable can reference a large collection of data.
Often you will have to store a large number of values during the execution of a
program. Suppose, for instance, that you need to read 10 numbers, compute their
average, and find out how many numbers are above the average. Your program first
reads the numbers and computes their average, then compares each number with
the average to determine whether it is above the average. In order to accomplish
this task, the numbers must all be stored in variables. You have to declare 100
variables and repeatedly write almost identical code 100 times. Writing a program
this way would be impractical. So, how do you solve this problem?
An efficient, organized approach is needed. Java and most other high-level languages
provide a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. In the present case, you can store all 100 numbers into
an array and access them through a single array variable. The solution may look like
this:
import java.util.Scanner;
public class arrayAnalyzeNumber {
public static void main(String[] args) {
final int NUMBER_OF_ELEMENTS = 10;
double[] numbers = new double[NUMBER_OF_ELEMENTS];
double sum = 0;
}
The program creates an array of 10 elements, stores numbers into the array, adds
each number to sum, and obtains the average. It then compares each number in the
array with the average to count the number of values above the average.
Array Basics
Once an array is created, its size is fixed. An array reference variable is used to
access
the elements in an array using an index.
An array is used to store a collection of data, but often we find it more useful to think
of an array
as a collection of variables of the same type. Instead of declaring individual variables,
such as
number0, number1, . . . , and number99, you declare one array variable such as
numbers and
use numbers[0], numbers[1], . . . , and numbers[99] to represent individual
variables.
elementType[] arrayRefVar;
The elementType can be any data type, and all elements in the array will have the
same
data type. For example, the following code declares a variable myList that
references an
Note
You can also use elementType arrayRefVar[] to declare an array variable. This
style comes from the C language and was adopted in Java to accommodate C
programmers. The style elementType[] arrayRefVar is preferred.
Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array
variable does not
allocate any space in memory for the array. It creates only a storage location for the
reference to
an array. If a variable does not contain a reference to an array, the value of the
variable is null.
You cannot assign elements to an array unless it has already been created. After an
array variable
is declared, you can create an array by using the new operator with the following
syntax:
This statement does two things: (1) it creates an array using new
elementType[arraySize]; (2) it assigns the reference of the newly created array to
the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the
array to
the variable can be combined in one statement as:
elementType[] arrayRefVar = new elementType[arraySize];
or
elementType arrayRefVar[] = new elementType[arraySize];
Here is an example of such a statement:
double[] myList = new double[10];
This statement declares an array variable, myList, creates an array of ten elements
of double
type, and assigns its reference to myList. To assign values to the elements, use the
syntax:
arrayRefVar[index] = value;
Array Initializers
Java has a shorthand notation, known as the array initializer, which combines the
declaration,
creation, and initialization of an array in one statement using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
For example, the statement
Processing Arrays
When processing array elements, you will often use a for loop—for two reasons:
■ All of the elements in an array are of the same type. They are evenly processed in
the
same fashion repeatedly using a loop.
■ Since the size of the array is known, it is natural to use a for loop.
Assume the array is created as follows:
double[] myList = new double[10];
2. Initializing arrays with random values: The following loop initializes the array
myList with random values between 0.0 and 100.0, but less than 100.0.
for (int i = 0; i < myList.length; i++) {
myList[i] = Math.random() * 100;
System.out.println(myList[i]);
}
4. Summing all elements: Use a variable named total to store the sum. Initially total
is 0. Add each element in the array to total using a loop like this:
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
5. Finding the largest element: Use a variable named max to store the largest
element. Initially max is myList[0]. To find the largest element in the array myList,
compare each element with max, and update max if the element is greater than
max.
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
}
6. Finding the smallest index of the largest element: Often you need to locate the
largest element in an array. If an array has more than one largest element, find the
smallest index of such an element. Suppose the array myList is {1, 5, 3, 4, 5, 5}.
The largest element is 5 and the smallest index for 5 is 1. Use a variable named max
to store the largest element and a variable named indexOfMax to denote the index
of the largest element. Initially max is myList[0], and indexOfMax is 0. Compare
each element in myList with max, and update max and indexOfMax if the element
is greater than max.
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++) {
if {
max = myList[i];
indexOfMax = i;
}
}
7. Simplifying coding: Arrays can be used to greatly simplify coding for certain tasks.
For
example, suppose you wish to obtain the English name of a given month by its
If you didn’t use the months array, you would have to determine the month name
using
a lengthy multi-way if-else statement as follows:
if (monthNumber == 1)
System.out.println("The month is January");
else if (monthNumber == 2)
System.out.println("The month is February");
...
else
System.out.println("The month is December");
for-each Loops
Java supports a convenient for loop, known as a for-each loop or enhanced for loop,
which
enables you to traverse the array sequentially without using an index variable. For
example,
the following code displays all the elements in the array myList:
for (double u: myList) {
System.out.println(u);
}
You can read the code as “for each element u in myList, do the following.” Note that
the variable, u, must be declared as the same type as the elements in myList.
In general, the syntax for a for-each loop is
for (elementType element: arrayRefVar) {
// Process the element
}
You still have to use an index variable if you wish to traverse the array in a different
order or
change the elements in the array.
LAB ACTIVITY:
public class arrayRandom {
public static void main(String[] args) {
}
System.out.println("TOTAL: "+ total);
}
}