Arrays Java
Arrays Java
For example, if we want to store the names of 100 people then we can
create an array of the string type that can store 100 names.
Here, the above array cannot store more than 100 names. The number of
values in a Java array is always fixed.
dataType[] arrayName;
dataType - it can be primitive data types like int , char , double , byte ,
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or
length of the array is 10.
In Java, we can declare and allocate the memory of an array in one single
statement. For example,
Here, we have created an array named age and initialized it with the values
inside the curly brackets.
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;
..
If the size of an array is n , then the last element of the array will be at
index n-1 .
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
In the above example, notice that we are using the index number to access
each element of the array.
We can use loops to access all the elements of the array at once.
Output
In the above example, we are using the for Loop in Java to iterate through
each element of the array. Notice the expression inside the loop,
age.length
Here, we are using the length property of the array to get the size of the
array.
We can also use the for-each loop to iterate through the elements of an
array. For example,
Example: Using the for-each Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
Output
Sum = 36
Average = 3.6
Here, we are using the length attribute of the array to calculate the size of
the array. We then calculate the average using:
As you can see, we are converting the int value into double . This is called
type casting in Java. To learn more about typecasting, visit Java Type
Casting.
Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays.
However, we can declare multidimensional arrays in Java.
class Main {
public static void main(String[] args){
ArrayList<String> animals = new ArrayList<>();
// Add elements
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
Output:
In the later tutorials, we will learn about the collections framework (its
interfaces and classes) in detail with the help of examples.