Array Declaration in Java

In Java, arrays are used to store multiple values of the same data type in a single variable. To declare an array in Java, you need to specify the data type of the elements and the array’s name.

Array declaration in Java can be done in two different ways. The first one is to declare and then initialize the array. And the second one is, to declare and initialize in a single line.

Let’s learn about them in detail.

1. Declare and then initialize the array

// Syntax for array declaration
dataType[] arrayName;

// Example of declaring an array of integers
int[] numbers;

// Example of declaring an array of strings
String[] names;

After declaring the array, you can initialize it by using the new keyword and specifying the size of the array in square brackets:

// Initializing the array with a specific size (e.g., 5)
numbers = new int[5];

// Initializing an array of strings with a specific size (e.g., 3)
names = new String[3];

2. Declare and initialize the array in one line

// Syntax for array declaration and initialization
dataType[] arrayName = new dataType[arraySize];

// Example of declaring and initializing an array of integers
int[] numbers = new int[5];

// Example of declaring and initializing an array of strings
String[] names = new String[3];

You can also initialize an array with specific values at the time of declaration using curly braces. See the example below:

// Initializing an array of integers with specific values
int[] numbers = {10, 20, 30, 40, 50};

// Initializing an array of strings with specific values
String[] names = {"Virat Kohli", "MS Dhoni", "Yuvraj Singh"};

Remember that arrays in Java are zero-indexed, meaning the first element is at index 0, the second element at index 1, and so on. You can access elements in the array using their index, like arrayName[index]. Also, the size of an array is fixed once it is initialized, so you cannot change the size of an array after it is created.

Sharing Is Caring: