Single array
A single array variable can reference a large collection of
data.
You will have to store a large number of data / values
during the execution of a program. Suppose that you need to store 200 numbers
to compute their average, sum or find maximum value. So first your computer
will read the numbers and should store in variables. Think you have to declare
200 values and repeatedly write almost identical code 200 times huh is it easy?
No you will fed-up soon. So how do you solve this problem? Most high level language
are provide data structure, the Array, which can store a fixed size collection
of elements of the same type.
Array – a collection of data or one can think array is a
collection of data in same type. Correct.
How to Declare a Array variable?
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 array of double elements.
int[] myList;
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 and
assign its reference to the variable with the following syntax:
arrayRefVar = new elementType[length];
elementType[] arrayRefVar = new elementType[arraySize];
or,
elementType arrayRefVar[] = new elementType[arraySize];
Examples of such a statements
char[] myList= new char [10];
To assign values to the element, use the syntax:
arrayRefVar[index] = value;
For example, the following code initializes the array.
myList[0] = 34;
myList[1] = 89;
myList[2] = 45;
myList[3] = 23;
myList[4] = 67;
This array can illustrate like this
int[] myList= new int[5]
myList[0]
|
34
|
myList[1]
|
89
|
myList[2]
|
45
|
myList[3]
|
23
|
myList[4]
|
67
|
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
double[] myList = {1.9, 2.9, 3.4, 3.5};
declares, creates, and initializes the array myList with
four elements, which is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
In my next post I hope to explain how to process arrays for
some purposes.
Thank you guys
No comments:
Post a Comment