Anonymous Array in Java

  • An array without name is known as anonymous array in java
  • As the array do not have any name so it can be used only once. 
  • Anonymous array is passed as an argument of method. 
  • Anonymous array is created and initialized in the same line.

How to Create Anonymous Array in Java?

A sample program is given below which shows that how 1D and 2D anonymous array can be created and used in java. In this program I have just created, initialized and passed two anonymous arrays in a method. In print() method I am printing the elements of the arrays. If you find any difficulty to understand the program then you can comment below and ask your queries.

class AnonymousArray
{
 static void print(int a[])
 {
  for(int i=0;i<a.length;++i)
   System.out.print(a[i]+" ");
 }

 static void print(int a[][])
 {
  for(int i=0;i<a.length;++i)
  {
   for(int j=0;j<a[i].length;++j)
    System.out.print(a[i][j]+" ");

   System.out.println("");
  }
 }
  
 public static void main(String...s)
 {
  //1d anonymous array 
  print(new int[]{10,20,30,40});

  System.out.println("n");
  
  //2d anonymous array 
  print(new int[][]{{10,20},{30,40},{50,60}});  
 }
}

Anonymous Array in Java

2 thoughts on “Anonymous Array in Java”

Leave a Comment

Your email address will not be published. Required fields are marked *