Font Awesome Icons


Java Arrays

An array is a collection of similar types of data which are of fixed-size and sequential. It can be thought of as a container that holds data (values) of one single type. Arrays in Java are also objects. They need to be declared and then created.

For example, we can create an array that can hold 100 or 200 values of int type.


Array Features:

  • Arrays are objects and created on the heap.

  • They can even hold the reference variables of other objects.

  • They are created during runtime.

  • The Array length is fixed.

  • All the elements are stored under one name in an array. This name is used any time we use an array.

  • The elements in the arrays are stored at adjacent positions.


How to declare an array?


dataType[] arrayName;
dataType – it can be primitive data types like int, char, double,float, byte, etc. or Java objects
arrayName – it is an identifier

int[] a;

a = new int[100];
Here, the size of the array is 100. This means it can hold 100 elements.
The above lines can be combined into a single statement in Java.

int[] a= new int[100];


Java Array Index:

In Java, each element in an array is associated with a number. The number is known as an array index. The array index always starts from 0.
we use the index number to access elements of the array. For example, to access the first element of the array is we can use a[0], and the second element is accessed using a[1] and so on.

Initialize an Array During Declaration:

int[] a = {9, 1, 12, 21, 8,4};

This statement creates an array named a and initializes it with the value provided in the curly brackets. The length of the array is determined by the number of values provided inside the curly braces separated by commas. In this example, the length is 6.


Array Example1:


class Array1 {
public static void main(String[] args) {

int[] age ={9, 1, 12, 21, 8,4};<—– // creates an array

for (int i = 0; i < 5; ++i) {
System.out.println(“Element at index ” + i +”: ” + age[i]); <—–// access elements of tha array

Note: The size of an array is also known as the length of an array. Once the length of the array is defined, it cannot be changed in the program.


Array Example2:

public class Array2
public static void main(String[] args) {
int[] a = new int[4];
a[2] = 14;
a[0] = 4;
a[1] = 2;
a[3] = 3;

for (int i = 0; i < 4; ++i) {
System.out.println(“Element at index ” + i +”: ” + a[i]);