Array in java

Java Array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.

   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 Array

  • Size Limit: We can store 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 Array in java

there are two types

  • Single dimension Array
  • Multidimensional Array

Single dimension Array

Syntax to Declare an Array in java

  • dataType[] arr; (or)
  • dataType []arr; (or)
  • dataType arr[];

Example

  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;  
  
//printing array  
for(int i=0;i<a.length;i++)//length is the property of array  
System.out.println(a[i]);  
  
}}  

Multidimensional array in java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax

1.dataType[][] arrayRefVar; (or)

2.dataType [][]arrayRefVar; (or)

3.dataTypearrayRefVar[][]; (or)

4.dataType []arrayRefVar[];

Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional 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();  
}  
  
}}  
	

Copying a java array

We can copy an array to another by the arraycopy method of System class.

Syntax of array copy method

 public static void arraycopy(  
Object src, int srcPos,Object dest, int destPos, int length  
)  

Example of array copy method

  class TestArrayCopyDemo {  
    public static void main(String[] args) {  
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',  
                'i', 'n', 'a', 't', 'e', 'd' };  
        char[] copyTo = new char[7];  
  
        System.arraycopy(copyFrom, 2, copyTo, 0, 7);  
        System.out.println(new String(copyTo));  
    }  
}  

Example of 2 matrices in java

 class Testarray {
	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  
}  
  
}}