A one-dimensional array in Java is an array with a bunch of values that are declared with a single index. Here data are stored in a single column as shown below in an example.
Array declaration:
1 2 3 4 5 | data_type [] array_Name; or data_type[] array-name or data_type array-name[]; |
Example:
1 2 3 4 | //to store integer value int intArray[]; or int []intArray; |
An array declaration has two components:
The type that is the data-type of an element and the name that is given by user choice with the brackets[].
Array initialization:
To initialize an array new is used and it appears as follows:
1 | var-name = new data-type [size]; |
Example:
1 | Array = new int[10]; |
We can also set by combining declaration and initialization in the following ways:
1 2 3 | dataType[] arrayRefVar = new dataType[arraySize]; or dataType[] arrayRefVar = {value0, value1, ..., valuek}; |
Accessing an array element:
Array elements can be accessed by using its index number, where each element is assigned by one index number.
Example:
1 | age[2] = 14; // insert 14 to third element |
Example of a one-dimensional array in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class ArrayTest { public static void main(String args[]) { int a[]={10,22,4,7};//declaration, instantiation and initialization //displaying array for(int i=0; i < a.length; i++) { System.out.println(a[i]); } } } |
Output:
1 2 3 4 | 10 22 4 7 |