dsa

Java Arrays

In this tutorial, we will learn to work with arrays in Java. We will learn to declare, initialize, and access array elements with the help of examples.

Normally, an array is a collection of similar type of elements which has contiguous memory location.Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the 1st element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Types of Array in java

Java Array Index

In Java, each element in an array are associated with a number. The number is known as an array index. We can access elements of an array by using those indices.
For example,

int[] age = new int[5];
Java array index
Java Array Index

Here, we have an array of length 5. In the image, we can see that each element consists of a number (array index). The array indices always start from 0. Now, we can use the index number to access elements of the array. For example, to access the first element of the array is we can use age[0], and the second element is accessed using age[1] and so on.

Instantiating an Array in Java

In Java, we can initialize arrays during declaration or you can initialize later in the program as per your requirement.
Initialize an Array During Declaration Here's how you can initialize an array during declaration.


int[] age = {12, 4, 5, 2, 5};

This statement creates an array named age 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 our example, the length of age is 5.

Elements are stored in the array
Java Arrays initialization

One-Dimensional Arrays :

A one-dimensional array (or single dimension array) is a type of linear array. Accessing its elements involves a single subscript which can either represent a row or column index.
Syntax to Declare an Array in Java

dataType[] arr; (or)  
dataType []arr; (or)  
dataType arr[];  

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example of Java Array

//Java Program to illustrate how to declare, instantiate, initialize  
//and traverse the Java array.  
class Testarray{  
public static void main(String args[]){  
int a[]=new int[5];//declaration and instantiation  
a[0]=100;//initialization  
a[1]=200;  
a[2]=700;  
a[3]=400;  
a[4]=500;  
//traversing array  
for(int i=0;i
System.out.println(a[i]);  
}
    } 
    
    Output:
100
200
700
400
500
     

Following are some important point about Java arrays.