How to Declare and Initialize Array in Java: Simple Guide
In Java, you declare an array using
type[] arrayName; and initialize it with new type[size] or directly with values using type[] arrayName = {value1, value2, ...};. This creates a fixed-size collection of elements of the specified type.Syntax
To declare an array, specify the type followed by square brackets and the array name. To initialize, use the new keyword with the type and size, or assign values directly.
- Declaration:
type[] arrayName; - Initialization with size:
arrayName = new type[size]; - Declaration and initialization with values:
type[] arrayName = {value1, value2, ...};
java
int[] numbers; // Declaration numbers = new int[5]; // Initialization with size String[] fruits = {"Apple", "Banana", "Cherry"}; // Declaration and initialization with values
Example
This example shows how to declare an integer array, initialize it with values, and print each element.
java
public class ArrayExample { public static void main(String[] args) { int[] scores = {90, 80, 70, 60, 50}; for (int i = 0; i < scores.length; i++) { System.out.println("Score at index " + i + ": " + scores[i]); } } }
Output
Score at index 0: 90
Score at index 1: 80
Score at index 2: 70
Score at index 3: 60
Score at index 4: 50
Common Pitfalls
Common mistakes include forgetting to initialize the array before use, mismatching types, or trying to change the size after creation.
- Declaring without initialization leads to
NullPointerExceptionif accessed. - Array size is fixed; you cannot add or remove elements dynamically.
- Using wrong syntax like
int numbers = new int[5];instead ofint[] numbers = new int[5];.
java
int[] numbers; // Declared but not initialized // System.out.println(numbers[0]); // Error: compile-time error: variable numbers might not have been initialized // Wrong declaration: // int numbers = new int[5]; // Error: incompatible types // Correct way: int[] numbersCorrect = new int[5];
Quick Reference
| Action | Syntax Example |
|---|---|
| Declare array | int[] arr; |
| Initialize with size | arr = new int[10]; |
| Declare and initialize with values | int[] arr = {1, 2, 3}; |
| Access element | int x = arr[0]; |
| Get length | int len = arr.length; |
Key Takeaways
Declare arrays with
type[] name; and initialize with new type[size] or values.Array size is fixed after creation and cannot be changed.
Always initialize arrays before accessing elements to avoid errors.
Use
array.length to get the number of elements.Array elements are accessed using zero-based indexing.