How to create an Array in Java?

Java 8Object Oriented ProgrammingProgramming

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}
raja
Published on 08-Jan-2018 11:23:09
Advertisements