How to Create Array in Java: Syntax and Examples
In Java, you create an array by declaring its type followed by square brackets
[] and then initializing it with a size or values using new keyword or curly braces. For example, int[] numbers = new int[5]; creates an integer array of size 5.Syntax
To create an array in Java, you first declare the type of elements it will hold, followed by square brackets []. Then, you initialize the array either by specifying its size with new or by directly assigning values using curly braces.
- Declaration:
type[] arrayName; - Initialization with size:
arrayName = new type[size]; - Initialization with values:
arrayName = new type[]{value1, value2, ...};ortype[] arrayName = {value1, value2, ...};
java
int[] numbers = new int[5]; String[] names = {"Alice", "Bob", "Charlie"};
Example
This example shows how to create an integer array, assign values, and print them using a loop.
java
public class ArrayExample { public static void main(String[] args) { int[] numbers = new int[3]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } }
Output
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Common Pitfalls
Common mistakes when creating arrays in Java include:
- Forgetting to specify the size when using
new, which causes a compile error. - Trying to change the size of an array after creation, which is not allowed.
- Accessing indexes outside the array bounds, causing
ArrayIndexOutOfBoundsException. - Confusing array declaration syntax, such as placing brackets after the variable name instead of the type.
java
/* Wrong: missing size or values */ // int[] arr = new int[]; // Error: size or values needed /* Right: specify size or values */ int[] arr1 = new int[3]; int[] arr2 = {1, 2, 3};
Quick Reference
| Action | Syntax Example |
|---|---|
| Declare array | int[] numbers; |
| Create array with size | numbers = new int[5]; |
| Create and initialize array | int[] nums = {1, 2, 3}; |
| Access element | int x = numbers[0]; |
| Get length | int len = numbers.length; |
Key Takeaways
Declare arrays with the element type followed by square brackets, like
int[].Initialize arrays with
new type[size] or directly with values in curly braces.Array size is fixed after creation and cannot be changed.
Always access array elements within valid index range to avoid errors.
Use
array.length to get the number of elements in the array.