How to Declare an Array in Java?
In Java programming, arrays are one of the most essential data structures used to store multiple values of the same type in a single variable. Understanding how to declare an array in Java is very important. In this article, we will cover everything about array declaration, including the syntax, different ways to declare arrays, and common mistakes to avoid.
What is an Array Declaration in Java?
Declaring an array in Java means defining an array variable without assigning values. It simply creates a reference to an array but does not allocate memory. The actual memory allocation happens when the array is initialized.
Declaration of Array
Declaration of an Array in Java is very straightforward. First, we need to specify the data type of the element, followed by square brackets [], and then we need to write the name of an array.
Syntax:
dataType [] arrayName; // preferred syntax
- DataType: The type of elements the array will hold (e.g., int, double, String).
- arrayName: The name of the array variable.
Alternative Syntax:
dataType arrayName[]; // Less common
Note: This syntax is valid but not preferred.
Examples of Declaring Arrays
// Declares an array of integers
int[] arr;
// Declares an array of strings
String[] arr;
// Declares an array of doubles
double[] arr;
// Declares an array of integers with alternative syntax
int arr[];
Initialize an Array
Declaring an array only creates a reference. We first need to initialize an array before it can be used. We can initialize an array in two different ways which are listed below
1. Static Initialization
At the time of declaration we can assign value to the array
Syntax:
dataType[] arrayName = {value1, value2, value3};
Example:
int[] arr = {11, 22, 33, 44, 55};
String[] names = {"Geek1", "Geek2", "Geek3"};
Static initialization directly assigns values.
2. Dynamic Initialization
We can allocate memory for the array using the new keyword.
Syntax:
dataType[] arrayName = new dataType[arraySize];
Example:
// Array of size 5
int[] num = new int[5];
// Array of size 3
String[] names = new String[3];
Dynamic initialization allocates memory but leaves values unassigned (default values apply).
Note: The size of an array is fixed once it is set, it cannot be changed
Key Points
- Declaring an array only creates a reference, not the actual array.
- Memory is allocated only when we use the new keyword.
- We cannot specify the size of an array at the time of declaration.
- Java arrays are zero-indexed, means the first element is at index 0.