All Posts

Create an Array in Java

Create an Array in Java

In this tutorial, you will learn how to create an array in the Java programming language. An array is a collection of elements. We specify the size of the array at runtime. All the array elements are of the same data type. The array elements are commonly referred to using a single name, and individual elements are accessed using the index.

Declare an Array

The syntax to declare an integer array is as follows:

int  numbers[];  //declare an integer array

int  [] marks;  // another syntax to declare an array

Create an array

Create an array of 10 elements

int numbers  = new int[10];

Alternatively, you can declare and allocate memory in two steps.

//Declare an array

int  numbers[]; 

//Create an array

numbers =new int[10];

We can also provide a variable in the array size declaration.

/* Create an array where the size of the array is determined by the value of variable num */

int arr[] =new int[num];

 

—

Java Tutorials

Java Tutorial on this website: