Arrays in Java

Yuvaraj
16 min readJul 15, 2023

--

An array is a data structure used to store a collection of variables (elements) of the same type. The elements of an array are stored in a contiguous memory location. Where each data element can be accessed by its index number.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Array Index

Why do we need Arrays ?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Declaration of Arrays

To declare an array, define the variable type with square brackets.

Syntax:
dataType[] arrayName;

Example:
int[] arr;
OR // String[] cars;
int arr[];

Creating an array:

int[] arr = new int[10]; // To define the array's capacity, use the keyword new
Declaration & Initialization of an Array in Java

Access the Elements of an Array

You can access an array element by referring to the index number.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Output Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element

To change the value of a specific element, refer to the index number:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now output is Opel instead of Volvo

Array Length

You can access the length of an array (the number of elements it stores) via its length property. In C/C++, we need to use the sizeof operator.

To find out how many elements an array has, use the length property:

public class Program {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
}

// Output: 4
// Note: Array index starts from 0.

/* Method 1:
int[] arr = new int[10];
int arrayLength = arr.length;
System.out.println("Array Length is: " + arrayLength);

Method 2:
String[] city = {
"Delhi",
"Bhubaneswar",
"Mumbai",
"Bangalore",
"Kolkata",
"Hyderabad",
};
int arrayLength = city.length;
System.out.println("The size of the array is: " + arrayLength); */

/* Output:

Method 1: 10
Method 2: 6 */

The for loop is the most used loop when working with arrays, as we can use the length of the array to determine how many times to run the loop.

Example: Calculate the sum of all elements in an array by using for loops.

public class Pprogram {
public static void main(String[] args) {
int [] myArr = {6, 42, 3, 7};
int sum = 0;
for(int x=0; x<myArr.length; x++) {
sum += myArr[x];
}
System.out.println(sum);
}
}

// Output: 58

In the code above, we declared a variable named sum to store the result and assigned it 0. Then we used a for loop to iterate through the array, adding each element’s value to the variable.

The condition of the for loop is x<myArr.length as the last element’s index is myArr.length-1.

Enhanced for loop

The enhanced for loop (“for each” loop) is used to traverse elements in arrays. The advantages are that it eliminates the possibility of bugs and makes the code easier to read.

public class Program {
public static void main(String[] args) {
int[] primes = {2, 3, 5, 7};

for(int t: primes) { // Syntax: for(dataType item : array)
System.out.println(t);
}
}
}

/* Output:
2
3
5
7 */

The enhanced for loop declares a variable of a type compatible with the elements of the array being accessed. The variable will be available within the for block, and its value will be the same as the current array element.

So on each iteration of the loop, the variable t will be equal to the corresponding element in the array.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Single Dimensional Array

A single-dimensional array, or one-dimensional array, can be visualised as a single row or a column of array elements that are represented by a variable name and whose elements are accessed by index values. One-dimensional array in java must deal with only one parameter.

For example, the score of a series of football matches can be stored in a one-dimensional array.

Single Dimensional Array

Declaration of one-dimensional array

General form:

data-type var-name[];
OR
data-type[] var-name;
OR
data-type []var-name;

An array declaration has two components :

  • data-type: The data type determines the data type of each element present in the array-like char, int, float, objects etc.
  • var-name: It is the name of the reference variable which points to the array object stored in the heap memory.

[ ] is called subscript.

Construction of one-dimensional array in Java

There are mainly two ways to create an array in java :

  1. We can declare and store the values directly at the time of declaration :
int marks[ ] = { 90, 97, 95, 99, 100 };

Here JVM(Java Virtual Machine that drives the Java Code, converts Java bytecode into machine language) will assign five contiguous memory locations to store the values assigned to the array.

2. The second way of creating an array is by first declaring the array and then allocating the memory through the new keyword :

var-name = new type[size];     // int[] Number = new int[10];

Here size determines the max number of elements that can be stored in the array, To allocate memory using new we must specify the type and number of elements in the array. JVM has allocated memory locations to store 10 integers but we have not yet stored actual elements in the array. So, next, we’ll look at how do elements get stored in memory.

Memory representation after construction

The new int[10] initializes and creates an object referenced as number and assigns memory to the object in heap segment.

Array Memory Representation

Initialization of one-dimensional array

public class AssignValues {

public static void main(String args[]) {
int number[]; // array declared
number = new int[10]; // allocating memory, initialization
number[0] = 11;
number[1] = 22;
number[2] = 33;
number[3] = 44;
number[4] = 55;
number[5] = 66;
number[6] = 77;
number[7] = 88;
number[8] = 99;
number[9] = 100;
}
}

Note:

  • Since we chose int data type we can only add integer values to the array. So, the type of variable depends on the data type of an array.
  • The size of the array depends upon how many values we are providing at the time of initialization.
  • The size of one dimensional arrays cannot be changed once created.
Memory representation after initialization

General Syntax: Single Dimensional Array

data_type[] var_name = new data_type[];
OR
data_type var_name[] = {}; // curly braces encloses specialized set of values

For Example:

public class Example {

public static void main(String args[]) {
int arr[] = { 1, 5, 10, 15, 20 }; // initializing array
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + " "); // printing array elements
}
}
}


// Output : 1 5 10 15 20

Multi-Dimensional Arrays

The multi-dimensional arrays are arranged as an array of arrays. You can look it as a single container that stores multiple containers. Each element of a multidimensional array is an array itself.

The representation of the elements is in rows and columns. Thus, you can get a total number of elements in a multidimensional array by multiplying row size with column size. So if you have a two-dimensional array of 3×4, then the total number of elements in this array = 3×4 = 12.

For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can hold a maximum of 12 elements,

Examples:

Two dimensional array:
int[][] twoD_arr = new int[10][20];
// (or) int a[][] = new int[3][3];

Three dimensional array:
int[][][] threeD_arr = new int[10][20][30];
// (or) int a[][][] = new int[3][3][3];

Two Dimensional Array

2D array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns.

Declaration and Initialization of a Two Dimensional Array

In Java programming a two dimensional array can be declared and initialized in several ways.

int a[][]= new int[][] {{1,2,3}, {4,5,6}, {7,8,9}};
(or)
int a[][]= {{15,27,36}, {41,52,64}, {79,87,93}};
(or)
int a[][]= new int[3][3];

For Example :

In Java, there are various methods for two-dimensional arrays.

  • Using Standard Method
  • Using For Loop
  • Using Scanner
  • Using String

Standard Method


class TwodimensionalStandard
{
public static void main(String args[])
{
int[][] a={{10,20},{30,40}};//declaration and initialization
System.out.println("Two dimensional array elements are");
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]);
}
}

/* Output:

Two dimensional array elements are
10
20
30
40 */

For Loop Method

class TwodimensionalLoop
{
public static void main(String args[])
{
int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization
System.out.println("Two dimensional array elements are");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
System.out.println(a[i][j]);
}
}
}
}

/* Output:

Two dimensional array elements are
10
20
30
40
50
60 */

Scanner Method

import java.util.*;
class TwoDimensionalScanner
{
public static void main(String args[])
{

Scanner sc=new Scanner(System.in);
System.out.println("Enter Row length of an array : ");
int row=sc.nextInt();
System.out.println("Enter column length of an array : ");
int column=sc.nextInt();
int a[][]=new int[row][column];//declaration
System.out.print("Enter " + row*column + " Elements to Store in Array :\n");
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
a[i][j] = sc.nextInt();
}
}
System.out.print("Elements in Array are :\n");
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
System.out.println("Row ["+i+"]: Column ["+j+"] :"+a[i][j]);
}
}
}
}


/* Output:
Enter Row length of an array :
2
Enter column length of an array :
3
Enter 6 Elements to Store in Array :
1
2
3
4
5
6
Elements in Array are :
Row [0]: Column [0] :1
Row [0]: Column [1] :2
Row [0]: Column [2] :3
Row [1]: Column [0] :4
Row [1]: Column [1] :5
Row [1]: Column [2] :6 */

String Method

class TwoDimensionalString
{
public static void main(String[] args)
{
String[][] str = new String[][]{{"one", "two"}, {"three", "four"},{"five","six"}};
System.out.println("Two dimensional string array elements are :\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
System.out.println("str["+i+"]["+j+"]:"+str[i][j]);
}
}
}
}

/* Output:

Two dimensional string array elements are :

str[0][0]:one
str[0][1]:two
str[1][0]:three
str[1][1]:four
str[2][0]:five
str[2][1]:six */
class MultidimensionalArray {
public static void main(String[] args) {

// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

// calculate the length of each row
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}

// Here, we are using the length attribute to calculate the length of each row.

/* Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1 */

Three Dimensional Array

An array with three indexes (subscripts) is called a three-dimensional array in Java.

In other words, a three-dimensional array is a collection of one or more two-dimensional arrays, all of which share a common name.

Java three dimensional array is useful when we want to handle a group of elements belonging to another group. For example, suppose a college has three departments: Electronics, Computer Science, and Information Technology.

We can represent exam scores obtained by three students of each department in 3 different subjects like this:

Electronics department:

student1 scores: 75, 87, 69
student2 scores: 90, 87, 85
student3 scores: 56, 67, 76

Computer Science department:

student1 scores: 78, 67, 75
student2 scores: 87, 98, 76
student3 scores: 67, 56, 65

Information Technology department:

student1 scores: 72, 63, 72
student2 scores: 82, 91, 71
student3 scores: 64, 56, 66

The syntax below declares a three-dimensional array of variable scores, creates an array, and assigns its reference to scores:

// int[ ][ ][ ] scores = new int[3][3][3];

We can also use the shorthand notation to create and initialize the array as follows:

int[ ][ ][ ] scores = {
{{75, 87, 69}, {90, 87, 85},{56, 67, 76}},
{{78, 67, 75}, {87, 98, 76}, {67, 56, 66}},
{{72, 63, 72}, {82, 91, 71}, {64, 56, 66}}
};

Key points:

a) A multidimensional array in java is actually an array in which each element represents another array.

b) The difference between three-dimensional array and two-dimensional array is that 3D array consists of an array of 2D arrays, whereas, 2D array consists of an array of 1D arrays.

c) Three for loops (nested loop) are used to access each element in the tables.

d) First for loop is used to select each table.

e) Second for loop is used to select each row of the selected table.

f) Third for loop is used to access each element (value) in the row and table selected.

Three Dimensional (3D array) Example

Create a 3D array that consists of department-wise student marks. There are three departments: electronics, CS, and IT.

In each department, there are 3 students, and each student has scored in 3 subjects. We will calculate the total marks obtained and their percentage for each student.

public class ThreeDArray {
public static void main(String[] args)
{
String[ ] department = {"Electronics", "CS", "IT"};
int dept, st, sc, total = 0;
double perc = 0;

// Take the scores of students in a 3D array.
int[ ][ ][ ] scores = {
{{75, 87, 69}, {90, 87, 85},{56, 67, 76}},
{{78, 67, 75}, {87, 98, 76}, {67, 56, 66}},
{{72, 63, 72}, {82, 91, 71}, {64, 56, 66}}
};
// Display the scores of students from 3D array.
for(dept = 0; dept < 3; dept++)
{
for(int i = 0; i < 3; i++)
{
System.out.println("Department " +department[i]+ ": ");
for(st = 0; st < 3; st++)
{
System.out.println("Student" +(st + 1)+ " scores: ");
for(sc = 0; sc < 3; sc++)
{
System.out.print(scores[dept][st][sc]+ " ");
total += scores[dept][st][sc];
perc = (double)total/3;
}
System.out.println("\nTotal scores: " +total); // Displaying total marks of student.
System.out.println("Percentage: " +perc); // Displaying percentage.
total = 0; // reset total to zero.
}
System.out.println();
}
break;
}
}
}


/* Output:
Department Electronics:
Student1 scores: 75 87 69
Total scores: 231
Percentage: 77.0

Student2 scores: 90 87 85
Total scores: 262
Percentage: 87.33333333333333

Student3 scores: 56 67 76
Total scores: 199
Percentage: 66.33333333333333

Department CS:
Student1 scores: 75 87 69
Total scores: 231
Percentage: 77.0

Student2 scores: 90 87 85
Total scores: 262
Percentage: 87.33333333333333

Student3 scores: 56 67 76
Total scores: 199
Percentage: 66.33333333333333

Department IT:
Student1 scores: 75 87 69
Total scores: 231
Percentage: 77.0

Student2 scores: 90 87 85
Total scores: 262
Percentage: 87.33333333333333

Student3 scores: 56 67 76
Total scores: 199
Percentage: 66.33333333333333 */

String Array

A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string cannot be changed. The String Array works similarly to other data types of arrays.

Key points about the String Array:

  • It is an object of the Array.
  • It can be declared by the two methods; by specifying the size or without specifying the size.
  • It can be initialized either at the time of declaration or by populating the values after the declaration.
  • The elements can be added to a String Array after declaring it.
  • The String Array can be iterated using the for loop.
  • The searching and sorting operation can be performed on the String Array.

Declaration:

A String Array can be declared as follows:

String[] stringArray1   //Declaration of the String Array without specifying the size  
String[] stringArray2 = new String[2]; //Declarartion by specifying the size

Initialization:

String[] strAr1=new String[] {"Ani", "Sam", "Joe"}; //inline initialization  
2. String[] strAr2 = {"Ani", "Sam", " Joe"};
3. String[] strAr3= new String[3]; //Initialization after declaration with specific size
strAr3[0]= "Ani";
strAr3[1]= "Sam";
strAr3[2]= "Joe";

Adding Elements to a String Array

We can easily add the elements to the String Array just like other data types. It can be done using the following three methods:

  • Using Pre-Allocation of the Array
  • Using the Array List
  • By creating a new Array
  1. Pre-Allocation of the Array

In this method, we already have an Array of larger size.

For example, if we require to store the 10 elements, then we will create an Array of size 20. It is the easiest way to expand the Array elements.

// Java Program to add elements in a pre-allocated Array 

import java.util.Arrays;
public class StringArrayDemo {
public static void main(String[] args) {
String[] sa = new String[7]; // Creating a new Array of Size 7
sa[0] = "A"; // Adding Array elements
sa[1] = "B";
sa[2] = "C";
sa[3] = "D";
sa[4] = "E";
System.out.println("Original Array Elements:" + Arrays.toString(sa));
int numberOfItems = 5;
String newItem = "F"; // Expanding Array Elements Later
String newItem2 ="G";
sa[numberOfItems++] = newItem;
sa[numberOfItems++] = newItem2;
System.out.println("Array after adding two elements:" +
Arrays.toString(sa));
}
}

/* Output:
Original Array Elements:[A, B, C, D, E, null, null]
Array after adding two elements:[A, B, C, D, E, F, G] */

In this example, we have added two elements to a pre-allocated Array.

2. ArrayList

The array list is a data structure in the Java collection framework. We can easily add elements to a String Array using an array list as an intermediate data structure. The Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements at any time. It is found in the java.util package. It is like the Vector in C++.


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

public class StringArrayDemo1 {
public static void main(String[] args)
{
// Defining a String Array
String sa[] = { "A", "B", "C", "D", "E", "F" };
//
System.out.println("Initial Array:\n"
+ Arrays.toString(sa));
String ne = "G"; // Define new element to add
List<String>l = new ArrayList<String>(
Arrays.asList(sa)); // Convert Array to ArrayList
l.add(ne); // Add new element in ArrayList l
sa = l.toArray(sa); // Revert Conversion from ArrayList to Array
// printing the new Array
System.out.println("Array with added Value: \n"
+ Arrays.toString(sa)) ;
}
}


/* Output:

Initial Array:
[A, B, C, D, E, F]
Array with added value:
[A, B, C, D, E, F, G] */

3. Creating a New Array

In this method, we will create a new Array with a larger size than the initial Array and accommodate the elements in it. We will copy all the elements to the newly added Array.

// Java Program to add elements in a String Array by creating a new Array  

import java.util.Arrays;

public class StringArrayDemo2 {
public static void main(String[] args) {
//Declaring Initial Array
String[] sa = {"A", "B", "C" };
// Printing the Original Array
System.out.println("Initial Array: " + Arrays.toString(sa));
int length_Var = sa.length; //Defining the array length variable
String newElement = "D"; // Defining new element to add
//define new array with extended length
String[] newArray = new String[ length_Var + 1 ];
//Adding all the elements to initial Array
for (int i=0; i <sa.length; i++)
{
newArray[i] = sa [i];
}
//Specifying the position of the added elements ( Last)
newArray[newArray.length- 1] = newElement;
//make it original and print
sa = newArray;
System.out.println("updated Array: " + Arrays.toString(sa));
}
}


/* Output:

Initial Array: [A, B, C]
updated Array: [A, B, C, D] */

Jagged Array

A jagged array, also known as an array of arrays, is an array whose elements are arrays themselves, and these inner arrays can be of different lengths. Unlike a multidimensional array where each row has the same number of columns, a jagged array allows each row to have a different number of columns.

int[][] arr_name = {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

Each element of the main array is an array itself, and these inner arrays can have varying lengths. They are useful when dealing with datasets where rows have different numbers of elements, such as a list of students where each student can have a different number of subjects.

public class JaggedArrayExample {
public static void main(String[] args) {
// Declaring a 2D jagged array
int[][] jaggedArray = new int[3][];

// Initializing the jagged array
jaggedArray[0] = new int[]{1, 2, 3};
jaggedArray[1] = new int[]{4, 5};
jaggedArray[2] = new int[]{6, 7, 8, 9};

// Accessing elements of the jagged array
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}



// Output

/* 1 2 3
4 5
6 7 8 9 */

In this example, jaggedArray is a 2D array where the first row has 3 elements, the second row has 2 elements, and the third row has 4 elements. This demonstrates the flexibility of jagged arrays in handling different sizes of sub-arrays.

Anonymous Array

An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable.

Properties of Anonymous Arrays:

  • We can create an array without a name. Such types of nameless arrays are called anonymous arrays.
  • The main purpose of an anonymous array is just for instant use (just for one-time usage).
  • An anonymous array is passed as an argument of a method.

Note: For Anonymous array creation, do not mention size in []. The number of values passing inside {} will become the size.

Syntax:

new <data type>[]{<list of values with comma separator>};

Examples:

// anonymous int array 
new int[] { 1, 2, 3, 4};

// anonymous char array
new char[] {'x', 'y', 'z'};

// anonymous String array
new String[] {"Geeks", "for", "Geeks"};

// anonymous multidimensional array
new int[][] { {10, 20}, {30, 40, 50} };

Implementation:

// Java program to illustrate the concept of anonymous array


class Test {
public static void main(String[] args)
{
// anonymous array
sum(new int[]{ 1, 2, 3 });
}

public static void sum(int[] a)
{
int total = 0;

// using for-each loop
for (int i : a)
total = total + i;

System.out.println("The sum is: " + total);
}
}


/* Output:

The sum is: 6 */

In the above example, just to call the sum method, we required an array, but after implementing the sum method, we are not using the array anymore. Hence for this one-time requirement anonymous array is the best choice.

--

--