Java - Arrays: Declaring Array Variables
Java - Arrays: Declaring Array Variables
http://www.tutorialspoint.com/java/java_arrays.htm
Java provides a dat a st ruct ure, t he array, which st ores a fixed-size sequent ial collect ion of
element s of t he same t ype. An array is used t o st ore a collect ion of dat a, but it is oft en more useful
t o t hink of an array as a collect ion of variables of t he same t ype.
Inst ead 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] t o
represent individual variables.
This t ut orial int roduces how t o declare array variables, creat e arrays, and process arrays using
indexed variables.
// preferred way.
or
dataType arrayRefVar[];
//
No te: The st yle dataT ype[] arrayRefVar is preferred. The st yle dataT ype arrayRefVar[]
comes from t he C/C++ language and was adopt ed in Java t o accommodat e C/C++ programmers.
Example:
The following code snippet s are examples of t his synt ax:
double[] myList;
// preferred way.
or
double myList[];
//
The array element s are accessed t hrough t he index. Array indices are 0-based; t hat is, t hey st art
from 0 t o arrayRefVar.length-1.
Example:
Following st at ement declares an array variable, myList , creat es an array of 10 element s of double
t ype and assigns it s reference t o myList :
double[] myList = new double[10];
Following pict ure represent s array myList . Here, myList holds t en double values and t he indices are
from 0 t o 9.
Processing Arrays:
When processing array element s, we oft en use eit her for loop or foreach loop because all of t he
element s in an array are of t he same t ype and t he size of t he array is known.
Example:
Here is a complet e example of showing how t o creat e, init ialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
Max is 3.5
Example:
The following code displays all t he element s in t he array myList :
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
You can invoke it by passing an array. For example, t he following st at ement invokes t he print Array
met hod t o display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
SN
1