![](./write-blog/images/933247398-array-in-java-thumbnail.png)
Java Arrays: Definition and Usage Explained
Table of Content:
Introduction to Array
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data,
A single array variable can reference a large collection of data.
What is Array
An array is a collection of similar data types. or we can say array is a container object that hold values of homogenous type. the size of an array is fixed and cannot increase to accommodate more elements. The first element of an array starts with zero.
It is also known as static data structure because size of an array must be specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero to size-1.
In simple words, it’s a programming construct which helps to replace this
x0=0; x1=1; x2=2; x3=3; x4=4; x5=5;
with this …
x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5;
Features of Array
- It is always indexed. The index begins from 0.
- It is a collection of similar data types.
- It occupies a contiguous memory location.
Advantage of Java Array
- Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
- Random access: We can get any data located at any index position.
Disadvantage of Java Array
- Size Limit: We can store the only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Java Array
There are two types of array.
- Single Dimensional Array
- Multidimensional Array
Single Dimensional Array in java
Array Declaration
datatype[ ] identifier; or datatype identifier[ ];
Both are valid syntax for array declaration. But the former is more readable.
Example :
dataType[] arrayName; // preferred way. or dataType arrayName[]; // works but not preferred way.
Note ? The style dataType[] arrayName
is preferred. The style dataType arrayName[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example for another dataTypes
int[ ] arr; char[ ] arr; short[ ] arr; long[ ] arr; int[ ][ ] arr; // two dimensional array.
Initialization of Array
new
an operator is used to initializing an array.
Example:
int[ ] arr = new int[10]; //this creates an empty array named arr of integer type whose size is 10. or int[ ] arr = {10,20,30,40,50}; //this creates an array named arr whose elements are given. double[] myList = new double[10]; //creates an array of 10 elements of double type and assigns its reference to myList int intArray[] = new int[10]; // creates an array of 10 elements of int type and assigns its reference to intArray
Example:
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the array
Accessing array element
As mention earlier array index starts from 0. To access nth element of an array. Syntax
arrayname[n-1];
Example: To access 4th element of a given array
int[ ] arr = {10,24,30,50}; System.out.println("Element at 4th place" + arr[3]);
The above code will print the 4th element of the array arr
on console.
Note: To find the length of an array, we can use the following syntax: array_name.length
. There are no braces in front of length. It's not length().
Coding Example of array
We can declare, instantiate and initialize the java array together by:
double[] myList = {3.9, 5.9, 22.4, 31.5};
Program:
public class ArrayExample { public static void main(String[] args) { double[] myList = {3.9, 5.9, 22.4, 31.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } } }
Output:
This will produce the following result-
3.9 5.9 22.4 31.5 Press any key to continue . . .
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.
a[0]=10;//initialization index 0
Program:
Output:
This will produce the following result-
10 20 30 40 50 Press any key to continue . . .
Important of an array example
Save , Compile & Run the code. Observe the Output. If x is a reference to
an array, x.length
will give you the length of the array.
Unlike C, Java checks the boundary of an array while accessing an element in it.
Java will not allow the programmer to exceed its boundary.
class ArrayDemo{ public static void main(String args[]){ int array[] = new int[7]; for (int count=0;count<7;count++){ array[count]=count+1; } for (int count=0;count<7;count++){ System.out.println("array["+count+"] = "+array[count]); } } }Output:
This will produce the following result-
array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 5 array[5] = 6 array[6] = 7 Press any key to continue . . .
Coding Example of array
Here is a complete example showing how to create, initialize, and process arrays
Program:public class ArrayExample { public static void main(String[] args) { double[] myList = {3.9, 5.9, 22.4, 31.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }Output:
This will produce the following result-
3.9 5.9 22.4 31.5 Total is 63.7 Max is 31.5 Press any key to continue . . .
Array and Methods
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
Program:public class ArrayExample { static void findmin(int arr[]){ int min=arr[0]; for(int i=1;iOutput:arr[i]) min=arr[i]; System.out.println("Minimum value: "+min); } public static void main(String args[]){ int a[]={22,4,6,7}; findmin(a);//passing array to method } }
This will produce the following result-
Minimum value: 4 Press any key to continue . . .
Passing Array to method in java
Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original.
Program:class ArrayDemo { public static void passByReference(String a[]){ a[0] = "Changed"; } public static void main(String args[]){ String []b={"DOG","COW","PIG"}; System.out.println("Before Function Call "+b[0]); ArrayDemo.passByReference(b); // Function Call System.out.println("After Function Call "+b[0]); } }Output:
This will produce the following result-
Before Function Call DOG After Function Call Changed Press any key to continue . . .
foreach or enhanced for loop
J2SE 5 introduces special type of for loop called foreach loop to access elements of array. enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. Let us see an example of foreach loop.
Program:The following code displays all the elements in the array arr
class ArrayExample { public static void main(String[] args) { int[] arr = {10, 20, 30, 40}; for(int x : arr) { // Print all the array elements System.out.println(x); } } }Output:
This will produce the following result-
10 20 30 40 Press any key to continue . . .
Two Dimensional array
A multi-dimensional array is very much similar to a single dimensional array. It can have multiple rows and multiple columns unlike single dimensional array, which can have only one full row or one full column.
Syntax to Declare Multidimensional Array in java
datatype[ ][ ] identifier; or datatype identifier[ ][ ];
dataType[][] arrayRefVarName; (or) dataType [][]arrayRefVarName; (or) dataType arrayRefVarName[][]; (or) dataType []arrayRefVarName[];
Initialization of Array
new operator is used to initialize an array.
Example:
int[ ][ ] arrName = new int[10][10]; //10 by 10 is the size of array. or int[ ][ ] arrName = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}}; // 3 by 5 is the size of the array.
Accessing array element
For both, row and column, the index begins from 0.
Syntax:
array_name[m-1][n-1]
Example:
int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}}; System.out.println("Element at (2,3) place" + arr[1][2]);
Example to instantiate Multidimensional Array in java
int[][] arrName=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
arrName[0][0]=1; arrName[0][1]=2; arrName[0][2]=3; arrName[1][0]=4; arrName[1][1]=5; arrName[1][2]=6; arrName[2][0]=7; arrName[2][1]=8; arrName[2][2]=9;
Example of Multidimensional java array
Program: Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Arrayxample{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.print("\n"); } } }
Output:
1 2 3 2 4 5 4 4 5 Press any key to continue . . .
Addition of two matrices in java
Program: Let's see a simple example that adds two matrices.
class ArrayEx{ public static void main(String args[]){ //creating two matrices int a[][]={{2,4,6},{3,4,5}}; int b[][]={{7,1,2},{2,1,5}}; //creating another matrix to store the sum of two matrices int c[][]=new int[2][3]; //adding and printing addition of two matrices for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; System.out.print(c[i][j]+" "); } System.out.println();//new line } } }
Output:
9 5 8 5 5 10 Press any key to continue . . .