Declaring, creating and initializing in one line

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

Primitive

double avg = 90.5;
double[] studentAvgs = {70.0, 80.0, 75.6, avg, 98.0};
System.out.println("Array Length: " + studentAvgs.length);//prints 5

How this works?

  • Declares a double array reference variable named studentAvgs;
  • Creates a double array object in the memory with a length of five
    • Size of an array is determined by the number of comma-separated elements between the curly braces.
  • Initializes the array elements with the values 70.0, 80.0, 75.6, 90.5, 98.0
  • Assigns the array object to array reference variable studentAvgs.

The above code is equivalent to the following code:

double avg = 90.5;
double[] studentAvgs = new double[5];
studentAvgs[0] = 70.0;
studentAvgs[1] = 80.0;
studentAvgs[2] = 75.6;
studentAvgs[3] = avg;
studentAvgs[4] = 98.0;

The above method is useful because at the time you create an array you might not know the values that will be assigned to the array element.

Reference

package com.ibytecode.arrays;
class Person
{
	String name;
	public Person(String name) {
		this.name = name;
	}
}
public class ArrayMethod2 {
	public static void main(String[] args) {
		Person p1 = new Person("Kumar");
		Person p2 = new Person("Dev");
		Person[] persons = {p1, p2, new Person("Sri")};
		
	}
}

How many objects will be created in the memory?

  • One Person [] array object referenced by persons
  • Two Person object referenced by p1 and p2
  • Onw Person object reference by persons[2].

So, totally four objects will be created.

Multidimensional

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

studentAvgs[0] = an array of two doubles
studentAvgs[1] = an array of three doubles
studentAvgs[2] = an array of one doubles
studentAvgs[0] [0] = the double value 80.0
studentAvgs[1] [3] = the double value 85.5

Leave a Comment

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