Anonymous Array Creation

This is the third method for declaring, creating and initializing an array object in one line.

One Dimensional Array

Person[] arr;
arr = new Person[] {p1, p2};


Person[] arr = new Person[] {p1, p2}; 

When you use this method size should not be specified.
Person[] arr = new Person[2] {p1, p2}; //ERROR

This method is useful when we want to create a just-in-time array to use as an argument to a method that takes an array parameter.

package com.ibytecode.arrays;
class Person
	String name;
	public Person(String name) { = name;
public class ArrayMethod3 {
	public static void main(String[] args) {
		Person p1 = new Person("Kumar");
		Person p2 = new Person("Dev");
		method(new Person[] {p1, p2});
	public static void method(Person[] array)
		//use Person[] array here			

Two Dimensional Array

You can also use this method to create a two dimensional array as shown below.

double[][] studentAvgs = new double[][]{{80.0,90.0}, {75.5, 65.5, 85.5}, {98.0}};

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.