How to create an Array in Java?


In Java, you can create an array just like an object using the new keyword. The syntax of creating an array in Java using new keyword −

type[] reference = new type[10];

Where,

  • type is the data type of the elements of the array.
  • reference is the reference that holds the array.

And, if you want to populate the array by assigning values to all the elements one by one using the index −

reference [0] = value1;
reference [1] = value2;

For example, if you want to create an integer array of 5 elements you can create it using new keyword −

int[] myArray = new int[5];
You can populate the array element by element using the array index:
myArray [0] = 101;
myArray [1] = 102;
You can also create and initialize an array directly using the flower brackets ({}).
int [] myArray = {10, 20, 30, 40, 50}

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 19-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements