What is an array?
In Java, an array is a group of like-type variables which are sequent addresses on memory. The size of an array is absolute and cannot be changed during program execution.
The elements in an array are indexed by number and start with 0. The index of an element is like its address which helps us access the element’s value.
The following is an example of an array of the integers.

In Java, an array may be 1 dimension , 2 dimensions or n-dimensions. in 2 dimensions array, the element is indexed by 2 values which are row and column. For example:

Declaring an array in Java
Declaring an array in java with empty value:
//1 dimension < data type >[] name-of-variable = new < data type >[leng-of-array]; //2 dimensions < data type >[][] name-of-variable = new < data type >[num-of-rows][num-of-columns];
//1 dimension array int[] arr = new int[10]; //2 dimensions array int[][] arrb = new int[5][6]
Declaring an array with existed values:
int[] a = {1,2,3,4}; String[][] str = {{"this", "is", "the", "first", "row"}, {"this", "is", "the", "second", "row"}};
Assigning and accessing the values
Assigning the values into an empty array, with a short array, we can adding the values by selecting the index.
int[] arr1 = new int[3]; arr1[0] = 2; arr[1] = 3; arr[2] = 4;
However, in the case of longer array, we have to use another way to adding the values. Using for loop is an example.
int[] arr = new int[30]; int values = 1; for(int i = 0; i < arr.length; i++){ arr[i]= values; values+=2; } // the array will be [1,3,5,7 ....];
Similar with assigning value, we can access the value by using the index of value. For example:
String[] arr = {"this","is","a","string"}; System.out.println(arr[2]);
The out put will be
a
Or in the case we want to print all of the elements, we can use the For each loop
String[] arr = {"this","is","a","string"}; for(String str : arr){ System.out.println(str); }
the output will be
this
is
a
string
For printing the whole array
import java.util.*; public class arraysTest{ public static void main(String[] args){ String[] arr = {"this","is","a","string"}; System.out.println(Arrays.toString(arr)); } }
The output will be
[this, is , a, string]
Conclusion
We have gone through some basic things about array in Java. In part 2, I will write about some useful methods of Array class in java. Thanks for your reading.
Leave a Reply