Java Array

How to declare a Java array, create it, initialize, and access elements? An Array is a container object that holds a collection of similar types of elements (type may be an integer, float, long, etc.). It means we cannot store multiple data type values.

Scenario for Java Array: In our previous articles, we saw variable declaration and initialization, and they are pretty good for initializing a few variables. What if we want to store 100 employee salaries? Is it worth creating 100 variables and assigning those values? What happens if it is 150 employees? To handle this type of situation, it introduced the concept of arrays.

For example, an integer array will store all the integer elements. If you try inserting a float or char value, it will throw an error. The length of it is decided when we are creating it. Once it is created, the length is fixed. We have 3 types of arrays in Java Programming.

  1. One Dimensional
  2. Java Two Dimensional
  3. Java Multi-Dimensional
    • Three Dimensional
    • Four Dimensional etc

Java array declaration or Syntax

The following code snippet will show you the most basic way of an array declaration:

Data_Type[] Array_Name;
  • Data_type: It will decide the type of elements the array will accept. For example, If we want to store integer values, the Data Type will be declared as an int. To store Float values, the Data Type is a float
  • Array_Name: This is the name you want to give. For example, students, age, marks, emp.

Similarly, you can declare the remaining type of one-dimensional arrays as follows:

int [] anIntegerArray; 
byte[] anByteArray; 
short[] anShortArray; 
long[] anLongArray; 
float[] anFloatArray; 
double[] anDoubleArray; 
boolean[] anBooleanArray;
char[] anCharArray; 
String[] anStringArray;

Create a Java Array

To create an array, we have to use the New operator.

Data_Type[] Array_Name = new Array_Name[Array_Size];

Array_Size: Number of elements it can hold or store. For example, if Array_Size =10, it will hold 10 values.

If you have already initialized an array, then

int [] anIntegerArray; // Declaration

// Crating it
anIntegerArray = new int[10];

For Example, int[] Student_Marks = new int[10];

  1. We used int as the data type to declare an array. So, the above one will accept only integers. If we try to add float values, then it will throw an error.
  2. Student_Age is the name.
  3. The size of it is ten. It means Student_Marks will only accept ten integer values.
    • If we try to store more than ten, it throws an error.
    • We can store less than 10. For Example, If we store three integer values, the remaining two will be initialized to the default value (0).

Java Array Initialization first approach

There are multiple ways to initialize them and the first approach of declaring and Creating a one-dimensional Array in this Programming.

int[] Student_Marks = new int[3];

Initializing elements in the more traditional way

Student_Marks[0] = 15; // Initializing First elements at position 0
 Student_Marks[1] = 45; // Initializing elements at position 1
Student_Marks[2] = 65; // First elements at position 2

Initialize array at the declaration

In this approach, We initialize the Java array at the declaration time only.

int[] anIntegerArray = {15, 25, 35, 45, 55}

Here, We did not mention the size. However, the Javac is intelligent enough to determine the size by checking the number of elements.

Creating an array without size

Although this approach works without any error, this is not the preferred way to initialize in Java Programming.

int Employees[ ] = {1, 2, 3, 4, 5}

Java array initialization using a for loop

The above 3 methods are good for storing a small number of items in an array. What if we want to store 50, 100, or more values? It will be torture to add all of them using any of the above-mentioned approaches. To resolve this, we can use the loop concept to store data:

int i, Employees[100];

for (i =0; i < 100 ; i++)
 {
   Employees[i] = i * 2;
 }

TIP: To store the elements, we can use a Java While Loop and a Java Do While Loop.

Fifth Approach to create an array

The fifth approach of creating an array in Java programming language includes the declaration and initialization of a few values.

int[] anIntegerArray = new int[5];
anIntegerArray[0] = 10;
anIntegerArray[1] = 20;
anIntegerArray[2] = 30;

Here we declared an anIntegerArray array of size 5, but we only assigned three values to it. In this condition, the remaining values are assigned to default values (0 in this case).

The above one will be:

anIntegerArray[0] = 10
anIntegerArray[1] = 20
anIntegerArray[2] = 30
anIntegerArray[3] = 0
anIntegerArray[4] = 0

Accessing Java Array Elements

We use the index position to access the array element. We can access or alter/change the item using an index inside square brackets. The index value starts at 0 and ends at n-1, where n is the size or length.

For example, if it stores ten elements, the array indices start at 0 and end at 9. To access or modify the first value, use Array_Name[0] and to access or alter the 10th value, use Array_Name[10]. Let us see the example for better knowledge of accessing the array elements:

package ArrDefinitions;

public class ArrTest {

	public static void main(String[] args) {
		int[] anIntegerArray = {15, 25, 35, 45, 55, 65};

		System.out.println(anIntegerArray[0]);
		System.out.println(anIntegerArray[1]);
		System.out.println(anIntegerArray[2]);
		System.out.println(anIntegerArray[3]);
		System.out.println(anIntegerArray[4]);
		System.out.println(anIntegerArray[5]);
	}
}
15
25
35
45
55
65

TIP: I suggest you refer to the array methods article to see the list of built-in functions to work on arrays, such as array copy, sorting, etc.

Java Array example

We will declare an integer array of size ten. Then we will sum those ten values and displays the output.

package ArrayDefinitions;

public class JavaArray {

	public static void main(String[] args) {
		int i, Sum =0;
		int [] anIntegerArray = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
		
		for(i = 0; i < anIntegerArray.length; i++) {
			Sum = Sum + anIntegerArray[i];
			
			System.out.format("Addition of %d to Sum = %d \n", anIntegerArray[i], Sum);
		}
		System.out.format("Sum of the elemts in anIntegerArray = %d \n", Sum);
	}
}
Java Array example

In this array example Program, We declared 1 One Dimensional anIntegerArray[] with 10 elements and also declared i to iterate and access elements,

int [] anIntegerArray = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

The for loop iterate every array element in the anIntegerArray[4]. The condition inside the for loops (i < anIntegerArray.length) will ensure the Javac does not exceed the limit. Refer to the Java for loop.

  • Sum = Sum + anIntegerArray[i]; statement is used to add each and individual element present in the anIntegerArray to Sum variable.
  • System.out.format statement displays the Sum value after every iteration.
  • anIntegerArray.length finds the length of it.

Java Array First Iteration: The value of i will be 0, and the condition (i < 10) is True. So, it will start executing the statements inside the loop.

Sum = Sum + anIntegerArray[i]

=> Sum + anIntegerArray[0]

Sum = 0 + 10 = 10

The value of i will be incremented by 1

Second Iteration: The value of i is 1, and the condition (1 < 10) is True.

Sum = Sum + anIntegerArray[1] = 10 + 20 = 30

Third Iteration: After the increment, the i = 2, and the condition (2 < 10) is True.

Sum += anIntegerArray[2]
=> 30 + 30 = 60

Fourth Iteration: The value of i is 3, and the condition (3 < 5) is True.

Sum = 60 + 40 = 100

Fifth Iteration: i = 4, and the condition (4 < 10) is True.

Sum = 100 + 50 = 150

Java Array Sixth Iteration: i is 5, and the condition (5 < 10) is True.

Sum = 150 + 60 = 210

Seventh Iteration: After increment, i = 6, and the condition (6 < 10) is True.

Sum = 210 + 70 = 280

Eighth Iteration: i = 7, and the condition (7 < 10) is True.

Sum = 280 + anIntegerArray[7] => 280 + 80 = 360

9th Iteration: i is 8, and the condition (8 < 10) is True.

Sum = 360 + anIntegerArray[8] => 360 + 90 = 450

10th Iteration: i is 9, and the condition (9 < 10) is True.

Sum = Sum + anIntegerArray[9]
Sum = 450 + 100 = 550

11th Iteration: The value of i is 10, and the condition (10 < 10) is False. So, it will exit from the for loop and go to the last statement. Lastly, we used System.out.format statement to display the Sum.

Create a new Array in Java from user input

We may not create a fully dynamic array, but we can create a semi- dynamic array where we allow the user to decide the size and elements. Remember, once we declare the size, it is fixed, so an array cannot grow or shrink based on the array elements.

The following program allows the user to enter the array size and then enter the array items. The last for loop prints the total number of elements in the array.

import java.util.Scanner;

public class example {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n, i;

System.out.print("Enter the Array Size = ");
n = sc.nextInt();

int [] numArr = new int[n];

System.out.println("Enter the Array Items: ");
for(i = 0; i < n; i++)
{
numArr[i] = sc.nextInt();
}

System.out.println("Printing the Array Elements: ");
for(i = 0; i < n; i++)
{
System.out.print(numArr[i] + " ");
}

}
}
Enter the Array Size = 5
Enter the Array Items: 
10 30 70 80 100
Printing the Array Elements: 
10   30   70   80   100   

How to convert an array to an ArrayList in Java?

We can convert an array to an ArrayList, and the process depends on the array type. If the array is an object type, such as String, Integer, and so on, we can convert it directly to an ArrayList. However, if the given array is a primitive type such as int (not Integer), float, etc., then we must use a for loop.

In the example below, we used the object array (String). So, we use the built-in Arrays.asList function to convert an array to an ArrayList.

import java.util.ArrayList;
import java.util.Arrays;

public class NewExample {
public static void main(String[] args)
{
String[] strArr = {"Apple", "Banana", "Mango"};
ArrayList<String> al = new ArrayList<>(Arrays.asList(strArr));
System.out.println(al);
}
}
[Apple, Banana, Mango]

In the following example, we use the primitive int array. So, we use the for loop to iterate over each item in an array. Inside the for loop, we use the built-in add() function to add the array item to an ArrayList.

import java.util.ArrayList;
public class NewExample {
public static void main(String[] args)
{
int[] numArr = {11, 33, 55, 99, 100, 125};
ArrayList<Integer> al = new ArrayList<>();
for(int n: numArr)
{
al.add(n);
}
System.out.println(al);
}
}
[11, 33, 55, 99, 100, 125]

Difference between the Java Array and ArrayList

We can use both an array and an ArrayList to hold multiple items belonging to the same data type. However,

  • An array is fixed. Once we declare the size, we cannot change it. We can use the index position to access array items or update them.
  • An ArrayList is dynamic, and its size can be adjusted according to the items it holds.

Java Array Example

In the example below, we declared an array of size 4 and added 4 items to it.

public class example {
public static void main(String[] args)
{
int[] numArr = new int[4];
numArr[0] = 100;
numArr[1] = 200;
numArr[2] = 300;
numArr[3] = 400;

System.out.println(numArr.length);
}
}
4

If we try to add one more item to an array, it throws an Exception in thread “main”: ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4

numArr[4] = 500;

ArrayList Example

In the following example, we used an ArrayList to store integer values. First, we used the add() function to add two items to it. Next, we added two more items, and it allows. We can also remove items because an ArrayList can grow and shrink based on the existing elements.

import java.util.ArrayList;

public class example {
	public static void main(String[] args) {
		ArrayList<Integer> al = new ArrayList<>();
		al.add(100);
		al.add(200);
		System.out.println(al.size());

		al.add(300);
		al.add(400);
		System.out.println(al.size());
	}
}
2
4

Pass a Java array to a method by reference or Value

In general terms, Java is always pass-by-value. Having said that, when we pass an array to a function (or method), a copy of the original array’s reference is passed. So, we can modify the array items (something like replacing the existing second array item). However, we cannot assign a completely new array.

In the example below, the updateItem() method successfully updates the second array item. Whereas newItems() does not assign a completely new array to the original. Here, newItems() has a completely new array local to that method, and it won’t affect the original.

public class example {
static void updateItem(int[] a) {
a[2] = 222;
}

static void newItems(int[] a) {
a = new int[] { 9, 99, 999, 999 };
printItems(a);
}
static void printItems(int[] a) {
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {
int[] numArr = {1, 2, 3, 4};

updateItem(numArr);
System.out.println(numArr[2]);
printItems(numArr);

newItems(numArr);
System.out.println(numArr[2]);
printItems(numArr);
}
}
222
1 2 222 4 
9 99 999 999 
222
1 2 222 4