Open In App
Related Articles

Anonymous Array in Java

Improve Article
Improve
Save Article
Save
Like Article
Like

An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable.

Properties of Anonymous Arrays:

  • We can create an array without a name. Such types of nameless arrays are called anonymous arrays.
  • The main purpose of an anonymous array is just for instant use (just for one-time usage).
  • An anonymous array is passed as an argument of a method.

Note: For Anonymous array creation, do not mention size in []. The number of values passing inside {} will become the size.

Syntax: 

new <data type>[]{<list of values with comma separator>};

Examples:

// anonymous int array 
new int[] { 1, 2, 3, 4};  

// anonymous char array 
new char[] {'x', 'y', 'z'}; 

// anonymous String array
new String[] {"Geeks", "for", "Geeks"}; 

// anonymous multidimensional array
new int[][] { {10, 20}, {30, 40, 50} };

Implementation:

Java




// Java program to illustrate the
// concept of anonymous array
 
class Test {
    public static void main(String[] args)
    {
          // anonymous array
          sum(new int[]{ 1, 2, 3 });
    }
   
    public static void sum(int[] a)
    {
        int total = 0;
 
        // using for-each loop
        for (int i : a)
            total = total + i;
         
        System.out.println("The sum is: " + total);
    }
}


Output

The sum is: 6

Explanation: In the above example, just to call the sum method, we required an array, but after implementing the sum method, we are not using the array anymore. Hence for this one-time requirement anonymous array is the best choice. Based on our requirement, we can later give the name to the anonymous array, and then it will no longer be anonymous. 

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 Apr, 2022
Like Article
Save Article
Similar Reads
Related Tutorials