Java Arrays.....
Published: 2022-07-27 10:01:13

## Array ?

In your coding journey, you will find that arrays are used in many problems, no matter which programming language you choose, the usage of arrays will be there.

	An Array is a collection of similar data types stored in contiguous memory locations.
	At the time of declaration of an array, you must specify the type of data with the array name
	. You can access different elements present in an array using their index.

**Array declaration syntax in Java:**
int [] intArray;

•	An array is fixed in length i.e static in nature.
•	An array can hold primitive types and object references.
•	In an array when a reference is made to a nonexistent element, an IndexOutOfRangeException occurs

**Advantages**
o	Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o	Random access: We can get any data located at an index position.
**Disadvantages**
o	Size Limit: We can store only the 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 which grows automatically.

**There are two types of array.**
o	Single Dimensional Array
o	Multidimensional Array

**Example of Java Array**
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.Java Program : 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]=10;//initialization  
a[1]=20;  
a[2]=70;  
a[3]=40;  
a[4]=50;  
//traversing array  
for(int i=0;i<a.length;i++)//length is the property of array  
System.out.println(a[i]);  
}}  

```
**For-each Loop for Java Array**
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.

```
//Java Program to print the array elements using for-each loop  
class Testarray1{  
public static void main(String args[]){  
int arr[]={33,3,4,5};  
//printing array using for-each loop  
for(int i:arr)  
System.out.println(i);  
}}  

```
**Anonymous Array in Java**
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method.

```
//Java Program to demonstrate the way of passing an anonymous array to method.

class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}

```
**ArrayIndexOutOfBoundsException**
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBounds Exception if length of the array in negative, equal to the array size or greater than the array size while traversing the array.

**Multidimensional Array in Java** 
In such case, data is stored in row and column based index (also known as matrix form).
`Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column  
`
**Example of Multidimensional Java Array**
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

```
 //Java Program to illustrate the use of multidimensional array  

class Testarray3{  
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.println();  
}  
}}  

```
Output
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/si0auzuyqmjissi3md86.png)
**Copying a Java Array**
We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method

```
Syntax of arraycopy method
public static void arraycopy(  
Object src, int srcPos,Object dest, int destPos, int length  )  

//Java Program to copy a source array into a destination array in Java  

class TestArrayCopyDemo {  
    public static void main(String[] args) {  
        //declaring a source array  
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',  
                'i', 'n', 'a', 't', 'e', 'd' };  
        //declaring a destination array  
        char[] copyTo = new char[7];  
        //copying array using System.arraycopy() method  
        System.arraycopy(copyFrom, 2, copyTo, 0, 7);  
        //printing the destination array  
        System.out.println(String.valueOf(copyTo));  
    }  
}  

```
 Output
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7g3aechlf0ckdptub2t.png)

**Cloning an Array in Java**
Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the actual value. When the clone method is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array.
So in your example, int[] arr is a separate object instance created on the heap and int[] carr is a separate object instance created on the heap. (Remember all arrays are objects).
 

```
//Java Program to clone the array  
class Testarray1{  
public static void main(String args[]){  
int arr[]={33,3,4,5};  
System.out.println("Printing original array:");  
for(int i:arr)  
System.out.println(i);  
  
System.out.println("Printing clone of the array:");  
int carr[]=arr.clone();  
for(int i:carr)  
System.out.println(i);  
  
System.out.println("Are both equal?");  
System.out.println(arr==carr);  
  
}}  

```
 Output
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hx7g6z8mifuhjazbk7hw.png)

**Addition of 2 Matrices in Java**
Let's see a simple example that adds two matrices.

```
//Java Program to demonstrate the addition of two matrices in Java  

class Testarray5{  
public static void main(String args[]){  
//creating two matrices  
int a[][]={{1,3,4},{3,4,5}};  
int b[][]={{1,3,4},{3,4,5}};  
  
//creating another matrix to store the sum of two matrices  
int c[][]=new int[2][3];  
  
//adding and printing addition of 2 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
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awrg83idmfueg1w7lrng.png)

**Multiplication of 2 Matrices in Java**
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the second matrix which can be understood by the image given below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/no16iaxhb5vumdmtzkit.png)

```
//Java Program to multiply two matrices  
public class MatrixMultiplicationExample{  
public static void main(String args[]){  
//creating two matrices    
int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
    
//creating another matrix to store the multiplication of two matrices    
int c[][]=new int[3][3];  //3 rows and 3 columns  
    
//multiplying and printing multiplication of 2 matrices    
for(int i=0;i<3;i++){    
for(int j=0;j<3;j++){    
c[i][j]=0;      
for(int k=0;k<3;k++)      
{      
c[i][j]+=a[i][k]*b[k][j];      
}//end of k loop  
System.out.print(c[i][j]+" ");  //printing matrix element  
}//end of j loop  
System.out.println();//new line    
}    
}}  

```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdvkp0ugwa2jf4h4hbki.png)


```
** ** Happy reading friends..... ****
```