Java Arrays PDF
Java Arrays PDF
▪For example,
▪ double[ ] data;
▪ Here, data is an array that can hold values of type double.
▪In Java, we can declare and allocate the memory of an array in one single statement. For
example,
▪ double[] data = new double[10];
How to Initialize Arrays in Java?
▪ In Java, we can initialize arrays during declaration. For example,
//declare and initialize and array
▪ int[] age = {12, 4, 5, 2, 5};
▪ Note that we have not provided the size of the array. In this case, the Java compiler automatically specifies the
size by counting the number of elements in the array (i.e. 5).
▪In the Java array, each memory location is associated with a number. The number is known as an array index. We
can also initialize arrays in Java, using the index number. For example,
// declare an array
▪ int[] age = new int[5];
// initialize array
▪ age[0] = 12;
▪ age[1] = 4;
▪ age[2] = 5;
How to Access Elements of an Array in
Java?
▪Here is the syntax for accessing elements of an array,
// access array elements
▪ array[index]
Note:
◦ Array indices always start from 0. That is, the first element of an array is at index 0.
◦ If the size of an array is n, then the last element of the array will be at index n-1.
Example : Access Array Element using
indexes
Looping Through Array Elements
In Java, we can also loop through each element of the array. For example,
Example: Compute Sum and Average of
Array Elements
Multidimensional Arrays
Multidimensional Arrays
▪In this topic we will learn about the Java multidimensional array using 2-dimensional arrays and
3-dimensional arrays with the help of examples
▪A multidimensional array is an array of arrays.
Example,
int[][] a = new int[3][4];