Anonymous Arrays In Java

Anonymous Array in java

Sometimes we can declare array without name such type of arrays are known as anonymous arrays. The main purpose of anonymous arrays is just for instant use (one time usage). We can create anonymous arrays as follows:-

1-D Anonymous Array

new int[] = { 1,5,10,15,20};
new int[] = {1,4,8,10,12};

If we are creating an anonymous array we can’t declare the size of array. if we declare the size of an anonymous array we will get compile time error.

2-D Anonymous Array

We can also declare 2-D or Multi-Dimensional Anonymous Arrays.

new int[][] = new int{{1,2,3,4,5},{6,7,8,9,10}};
new int[][] = new int{{2,4,6,8,10},{12,14,16,18,20}};

Based on our requirement we can give the name of anonymous array and then it is no longer anonymous.

Anonymous Array Java Example

package Learning;

public class AnonymousArrays {

	public static void main(String[] args) {
		sum(new int[] {1,2,3});
		}
	
	public static void sum (int[] array) {
		int total=0;
		for(int item:array) {
			total =total+item ;
}
			System.out.println("Sum = "+ total);
                }
		}	
	
Anonymous Arrays in java

In the above Example just to call sum method we required an array but after completing sum method call we are not using that array anymore.

Anonymous array is the good choice in this type of conditions when array is required only one time.

Similar Java Tutorials

Leave a Comment