Anonymous Arrays in Java

An array without any name is called an anonymous array. Features of an anonymous array are:

  • It has no name (obviously).
  • It is created using the new keyword and pair of curly braces.
  • It is created and initialized at the same time.
  • It can be passed as an argument to a method.
  • It can be of any dimension. e.g Two-dimensional (discussed later).

1. Syntax

Syntax to declare a one-dimensional anonymous array is :


2. It is created an initialized at the same time

All anonymous arrays of any data type are created and initialized at the same time using the new keyword and pair of curly braces.

Output :

 


3. It can be passed as an argument to a method

Anonymous arrays are often used along with methods. When an array is needed only to pass a collection of data to a method and not needed afterwards, an anonymous array is made. Like one in the last example. Let’s have another example:

Output :

 


4. Two dimensional anonymous array

We can have an anonymous array of any dimension. To declare an anonymous array of N dimensions, you need to put N pair of brackets after the data type and accordingly use the curly braces.

Let’s have a concrete example of 2-dimensional anonymous array:

Output :

 


5. An anonymous array can be given a name as well.

If we want, we can give a name to an anonymous array. But after that it will no longer be anonymous.

Output :