Anonymous Array in java

An array without any name is anonymous array in java. They are mainly created for one time use only.

Note: Anonymous arrays can be passed as an argument of a method.

Syntax: Anonymous Int Array

new int[] { 15, 25, 23, 45, 34};  

Syntax: Anonymous Char Array

new char[] {'a', 'b', 'c', 'd'); 

Syntax: Anonymous String Array

new String[] {"Java", "JSP", "Servlet", "Spring"}; 

Syntax: Anonymous Multi-Dimensional Array

new String[][] { {"Java", "JSP", "Servlet", "Spring"}, {"MySQL", "Oracle"} };

Example 1

package com.w3schools;
 
public class Test {
  public static void main(String args[]){
	//Creating anonymous arrays		  
        System.out.println(new int[]{11, 22, 13, 14, 51}.length);  
        System.out.println(new int[]{21, 64, 65}[2]); 
  }
}

Output

5
65

Example 2

public class Main
{   
    static void total(int[] array) 
    { 
        int result = 0; 
 
        for (int num : array)  
            result = result + num; 
 
        System.out.println("Total: " + result); 
    } 
	public static void main(String[] args) {
    	total(new int[]{ 10, 5, 15 }); 
	}
}

Output

Total: 30

Interview Questions on Arrays