The Wayback Machine - https://web.archive.org/web/20210507033023/https://www.geeksforgeeks.org/anonymous-array-java/
Skip to content
Related Articles

Related Articles

Anonymous array in Java
  • Difficulty Level : Medium
  • Last Updated : 11 Dec, 2018

An array in Java without any name is anonymous array. It is an array just for creating and using instantly.

  • We can create an array without name, such type of nameless arrays are called anonymous array.
  • The main purpose of anonymous array is just for instant use (just for one time usage) .
  • Anonymous array is passed as an argument of method

Syntax:

// 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} };




// 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

NOTE: In the above example just to call sum method we required an array but after implementing sum method, we are not using 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 anonymous array and Then it will no longer be anonymous.
Example:

int[] x = new int[]{1, 2, 3};

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :