Java Arrays
Array is collection of similar type of elements in java programming. Each array are allocate memory on a heap area and array variable are store the reference of created array. Size of array is based on number of elements in array. When initial not provide array elements then size are compulsory.
Java array declaration
Array is declare in following ways in java programming.
//Both declaration of array are similar
String name[];
String []myName;
That is similar to define a normal variable, But there are only difference is that are used pair of ([]) square brackets after the data type.
In above example both arrays declaration are valid and similar. We can choose to anyone of this method. When we declare an array that means we can define the behaviour of array like which type of data it will store during program execution and what is the name of this array identifier. For example.
// Example of array declaration in Java
class MyArrays
{
public static void main(String[] args)
{
int[] intArrayElement; // array of integer elements
byte[] byteArrayElement; // array of byte elements
short[] shortsArrayElement; // array of short data elements
boolean[] booleanArrayElement; // array of boolean data elements
long[] longArrayElement; // array of long data elements
float[] floatArrayElement; // array of float data elements
double[] doubleArrayElement; // array of double data elements
char[] charArrayElement; // array of char data elements
// special case when create array of object
MyArrays[] obj; // Array of object element
}
}
Note that there is not possible to declare two same variable name of array in same scope. And All java array is dynamic allocated. And array are capable to store primitive data type value and object of class type. there is depend upon which type of array are declare.
Initialization of array element
In previous section we are declaring arrays. In this case compiler are know about that what type of value are storing by particular array. But there are not creating actual physical memory to array. In this section we are view example how to create dynamic memory to particular array variable and how to set initial value to variable. See this example.
// Create an array
class MyArray
{
public static void main(String[] args)
{
// Array of integer elements
int[] arr;
// Allocate memory to variable
// Here 7 indicates number of array elements
arr = new int[7];
}
}
In this example first is declared an integer array. After that allocated memory of this array by using of new operator. Note that new operator are create dynamic memory by using of data type and element size in array case.
Note that here is given two statement first declaring array and after that allocate memory to array variable. We can do this process by using single statement. See this example
// Create an array of 7 integer elements
int[] arr = new int[7];
This is a way to declare an array by number of element. But we are know about initial value of array element then we can initialize element in this way.
public class MyArray
{
public static void main(String[] args)
{
// Case A
// Element by new
int[] arr1 = new int[]
{
1 , 2 , 3 , 4 , 5 , 6 , 7
};
// Case B
// Elements without new
int[] arr2 = {
10 , 20 , 30 , 40 , 50 , 60
};
// Display size
System.out.println(arr1.length); // 7
System.out.println(arr2.length); // 6
}
}
In below image there are create created array are held the reference of new created array and array element are start with index zero and last element index are (elements-1).

Memory are allocated array element always is contiguous manner. This reason that are we can get array element by its index value.
When we provide all initial element to array then we can remove new statement in array initialization. For this example.
class MyArrays
{
public static void main(String[] args)
{
//Create array of string elements
String []codeLanguage = {
"C" , "C++" , "Java" , "C#" , "Kotlin" , "Swift"
};
}
}

Note that In this case compiler are decide the size of array by using of number of element in array. And size are cannot modified during program execution.
When we are declare an array elements and not set initial then compiler are provide default values to array elements.
public class DefaultArrayValue
{
public static void main(String[] args)
{
// Declare array elements
boolean[] myBoolElements = new boolean[3];
int[] myIntElements = new int[2];
float[] myFloatElements = new float[3];
String[] myStringElements = new String[3];
char[] myCharElements = new char[3];
double[] myDoubleElements = new double[2];
int index = 0;
System.out.println("Default Value of Boolean Arrays elements");
// Display Default value of array
for (index = 0; index < myBoolElements.length; index++)
{
System.out.println(myBoolElements[index]);
}
System.out.println("Default Value of Integer Arrays elements");
for (index = 0; index < myIntElements.length; index++)
{
System.out.println(myIntElements[index]);
}
System.out.println("Default Value of Float Arrays elements");
for (index = 0; index < myFloatElements.length; index++)
{
System.out.println(myFloatElements[index]);
}
System.out.println("Default Value of String Arrays elements");
for (index = 0; index < myStringElements.length; index++)
{
System.out.println(myStringElements[index]);
}
System.out.println("Default Value of char Arrays elements");
for (index = 0; index < myCharElements.length; index++)
{
System.out.println(myCharElements[index]);
}
System.out.println("Default Value of Double Arrays elements");
for (index = 0; index < myDoubleElements.length; index++)
{
System.out.println(myDoubleElements[index]);
}
}
}

Note that default value of character are unicode '\u0000' value and that us print null character. The result of above program is produce following output.
Default Value of Boolean Arrays elements
false
false
false
Default Value of Integer Arrays elements
0
0
Default Value of Float Arrays elements
0.0
0.0
0.0
Default Value of String Arrays elements
null
null
null
Default Value of char Arrays elements
Default Value of Double Arrays elements
0.0
0.0
There are similar way we can create arrays of object in particular class. let see an example.
class Student
{
int id;
String name;
Student(int id, String name)
{
this.id = id;
this.name = name;
}
void displayRecord()
{
System.out.println("id : " + id);
System.out.println("name : " + name);
}
public static void main(String[] args)
{
// Create array of objects
Student[] record = new Student[5];
for (int i = 0; i < record.length; i++)
{
// Set values of object
record[i] = new Student(i + 1, "Foo" + (i + 1));
}
record[1].displayRecord(); // Display records
}
}

Output
id : 2
name : Foo2
Update array elements
Get array element by index value, and similar way to modify of array element.
public class MyArrays
{
// Display Array elements
public static void dispaly(String[] arr)
{
for (String element: arr)
{
System.out.println(element);
}
System.out.println("------------");
}
public static void main(String[] args)
{
// Create array of string elements
String[] code = {
"C" , "C++" , "Java" , "C#" , "Kotlin" , "Swift"
};
System.out.println("Before Update");
dispaly(code);
// Update array element by index
code[2] = "Ruby";
code[5] = "JavaScript";
System.out.println("After Update");
dispaly(code);
}
}

Before Update
C
C++
Java
C#
Kotlin
Swift
------------
After Update
C
C++
Ruby
C#
Kotlin
JavaScript
------------
Element of array are mutable, It can be modified by specific array element index.
Multidimensional array
In this section we are view example how to implement multidimensional array in java programming. First view how to declare 2D array.
dataType [][] varName = new dataType[size][size];
See this are similar to one dimensional array only use one extra pair of ([]) square brackets in 2d array. See some examples.
//Create array of integers in 2 dimensional
//Size in form of 3 rows and 3 column
int [][] intData = new int[3][3];
//Create 2d String Array
//Size in form of 3 rows and 2 col
String[][] strData = new String[3][2];
//Create array of integers in 3 dimensional
//Size in form of (2 rows 3 column) * 3
float [][][] floatData = new float[2][3][2];
Here created are 3 array of 2 different dimension. Square bracket is decide the dimension of array and each dimension are describe the capacity of array element.
First array in above example are 2 dimensional because they are declare by [][] double square bracket and there size are [3][3]. So this array are capable to store (3X3) 9 elements of integer type.
Second array is also an two dimensional, That are store the element of string type. The size of this array are [3][2] here 3 rows and 2 column. So this array are capable to store maximum (3*2) 6 elements.
Third array size are 3 dimensional and it can hold floating values (Depends upon defining data type). Let view implemented all three examples one by one.
Implement 2d arrays
// Example of 2d Array
class Multidimensional
{
public static void main(String[] args)
{
// Create array of integers in 2 dimensional
// Size in form of 3 rows and 3 column
int[][] intData = new int[3][3];
int data = 0;
// Execute loop under the size of array
for (int row = 0; row < intData.length; row++)
{
// Execute loop under of rows column size
for (int col = 0; col < intData[row].length; col++)
{
data++;
// Set value
intData[row][col] = data;
}
}
// Execute loop under the size of array
for (int row = 0; row < intData.length; row++)
{
// Execute loop under of rows column size
for (int col = 0; col < intData[row].length; col++)
{
// Display element values
System.out.print(" " + intData[row][col]);
}
System.out.println(); // new line
}
}
}
Output
1 2 3
4 5 6
7 8 9

Similar way we can create 3 dimensional array.
// Example of 3d Array
class Multidimensional
{
public static void main(String[] args)
{
// Create array of integers in 3 dimensional
// Size in form of (2 rows 3 column) * 3
float[][][] floatData = new float[2][3][2];
float data = 0.9 f;
for (int dia = 0; dia < floatData.length; dia++)
{
// Execute loop under the size of array
for (int row = 0; row < floatData[dia].length; row++)
{
// Execute loop under of rows column size
for (int col = 0; col < floatData[dia][row].length; col++)
{
data++;
// Set value
floatData[dia][row][col] = data;
}
}
}
for (int dia = 0; dia < floatData.length; dia++)
{
// Execute loop under the size of array
for (int row = 0; row < floatData[dia].length; row++)
{
// Execute loop under of rows column size
for (int col = 0; col < floatData[dia][row].length; col++)
{
data++;
System.out.print(" " + floatData[dia][row][col]);
}
System.out.println();
}
System.out.println("");
}
}
}

Output
1.9 2.9
3.9 4.9
5.9 6.9
7.9 8.9
9.9 10.9
11.9 12.9
Jagged Array in Java
Jagged array is an array that are contains unknown number of column. That means initial are fixed that row size but not set number of column. See this example.
// Jagged Array
class Execution
{
public static void main(String[] args)
{
// static initialize element
int[][] number = {
{
1
},
{
1 , 2
},
{
1 , 2 , 3
},
{
1 , 2 , 3 , 4
},
{
1 , 2 , 3 , 4 , 5
},
{
7 , 8
}
};
for (int rows[]: number)
{
for (int data: rows)
{
System.out.print(" " + data);
}
System.out.println();
}
}
}

Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
7 8
Observe that initially provided array element are not contains the column size are same.
Basic operation of array
Get the length of array
// Java program
// Get the size of array elements
class MyArray
{
public static void main(String[] args)
{
int[] dataElement = {
1 , 2 , 3 , 4 , 5 , 6 , 8
};
int size = dataElement.length;
System.out.print("Size: " + size); //7
}
}
Output
Size: 7
shuffle of array elements
// Implementing shuffle of array elements
import java.util.concurrent.ThreadLocalRandom;
class Execution
{
// Implementing shuffle
public void shuffleElement(int[] array)
{
for (int index = 1; index < array.length; index++)
{
// Generates the next pseudorandom number.
int temp = ThreadLocalRandom.current().nextInt(index);
// Swap array element by index value
array[temp] += array[index];
array[index] = array[temp] - array[index];
array[temp] = array[temp] - array[index];
}
}
// Display array element
public void display(int[] array)
{
if (array.length == 0) return;
System.out.print("Array Element :");
for (int index = 0; index < array.length; index++)
{
System.out.print(" " + array[index]); // Display element
}
System.out.print("\n");
}
public static void main(String[] args)
{
Execution obj = new Execution();
int[] myArray = {
11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20
};
// Before
System.out.println("Before shuffle array elements");
obj.display(myArray);
System.out.println("After shuffle array elements");
// Shuffle array elements
obj.shuffleElement(myArray);
// After
obj.display(myArray);
System.out.println("Again of After shuffle array elements");
// Shuffle array elements
obj.shuffleElement(myArray);
// After
obj.display(myArray);
}
}
Output
Before shuffle array elements
Array Element : 11 12 13 14 15 16 17 18 19 20
After shuffle array elements
Array Element : 13 19 20 17 12 15 16 11 18 14
Again of After shuffle array elements
Array Element : 19 16 15 14 11 18 17 13 12 20
Convert array to string
// Java example for Convert array to string
import java.util.Arrays;
class Execution
{
public static void main(String[] args)
{
String[] myArray = new String[]
{
"Apple" , "Mango" , "Orange" , "Banana"
};
// Convert array to string
System.out.println(Arrays.toString(myArray));
String[][] multiArray = new String[][]
{
{
"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday"
},
{
"January" , "February" , "March" , "April" , "May"
}
};
// Convert multi-array to string
System.out.println(Arrays.deepToString(multiArray));
}
}
Output
[Apple, Mango, Orange, Banana]
[[Monday, Tuesday, Wednesday, Thursday, Friday], [January, February, March, April, May]]
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment