Question
How do I declare and initialize an array in Java?
Short Answer
By the end of this page, you will understand what an array is in Java, how to declare it, how to create it with a fixed size, and how to initialize it with values. You will also see common syntax patterns, step-by-step examples, and practical ways arrays are used in real Java programs.
Concept
An array in Java is a container that stores multiple values of the same type in a fixed-size structure.
When working with arrays in Java, there are usually two separate ideas:
- Declaration: telling Java that a variable will refer to an array
- Initialization/creation: actually creating the array in memory, optionally with values
For example:
int[] numbers;
This only declares an array variable named numbers. It does not create the array yet.
To create the array, you can do this:
numbers = new int[5];
Now Java creates an array that can hold 5 integers.
You can also declare and create it in one line:
int[] numbers = new int[5];
If you already know the values, you can initialize the array directly:
int[] numbers = {10, 20, 30, 40, 50};
Arrays matter because they are one of the most basic ways to store grouped data. They are used in loops, algorithms, input processing, and as the foundation for many other data structures.
Mental Model
Think of an array like a row of numbered lockers.
- The array variable is the name of the locker row
- Each element is one locker
- The index is the locker number
- The value is what is stored inside that locker
Example:
int[] scores = {90, 85, 78};
You can imagine this as:
- locker
0→90 - locker
1→85 - locker
2→78
The important rule is that Java arrays start at index 0, not 1.
Also, once the row of lockers is created, the number of lockers cannot change. That is why arrays are called fixed-size.
Syntax and Examples
Basic syntax
1. Declare an array
int[] numbers;
This tells Java that numbers will refer to an array of integers.
2. Create an array with a size
int[] numbers = new int[5];
This creates space for 5 integers. Because they are int, Java fills them with the default value 0.
3. Declare first, initialize later
int[] numbers;
numbers = new int[3];
This is useful when you do not want to create the array immediately.
4. Initialize with values
int[] numbers = {1, 2, 3, 4, 5};
Java automatically creates the array and stores these values.
5. Use with explicit values
Step by Step Execution
Consider this example:
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
System.out.println(numbers[1]);
Step-by-step
-
int[] numbers = new int[3];- Java creates an array that can hold 3 integers.
- Since it is an
intarray, the default values are:numbers[0] = 0numbers[1] = 0numbers[2] = 0
-
numbers[0] = 10;- The first element becomes
10.
- The first element becomes
-
numbers[1] = 20;- The second element becomes
20.
- The second element becomes
Real World Use Cases
Arrays are used when you need to store a fixed number of items of the same type.
Common examples
- Game scores
- Store a list of player scores
- Monthly data
- Store 12 monthly sales values
- Sensor readings
- Keep the latest measurements from a device
- Student marks
- Store exam results for a class
- Command-line arguments
- Java programs receive command-line input as a
String[] args
- Java programs receive command-line input as a
Example: storing weekday names
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
Example: fixed-size temperatures
double[] temperatures = new double[7];
temperatures[0] = 21.5;
temperatures[1] = 22.0;
Arrays are especially useful when the number of elements is known ahead of time.
Real Codebase Usage
In real Java projects, developers use arrays when a collection has a known fixed size or when working with APIs that expect arrays.
Common patterns
Looping through arrays
int[] numbers = {5, 10, 15};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Enhanced for loop
String[] names = {"Ana", "Ben", "Chris"};
for (String name : names) {
System.out.println(name);
}
This is commonly used when you only need the values, not the indexes.
Validation before access
if (numbers.length > 0) {
System.out.println(numbers[0]);
}
This avoids index errors.
Method parameters
public static int sum(int[] values) {
;
( value : values) {
total += value;
}
total;
}
Common Mistakes
1. Declaring an array without creating it
Broken code:
int[] numbers;
numbers[0] = 10;
Problem:
numbersis declared, but no array has been created yet.
Fix:
int[] numbers = new int[3];
numbers[0] = 10;
2. Going outside the array bounds
Broken code:
int[] numbers = new int[3];
numbers[3] = 40;
Problem:
- Valid indexes are
0,1, and2 - Index
3causesArrayIndexOutOfBoundsException
Fix:
Comparisons
Array declaration styles
Both of these are valid in Java:
int[] a;
int a[];
But this is more common and clearer:
int[] a;
Array with size vs array with values
| Syntax | Meaning |
|---|---|
new int[5] | Creates an array of 5 integers with default values |
{1, 2, 3} | Creates an array with specific values |
new int[]{1, 2, 3} | Creates an array with specific values using explicit new |
Array vs ArrayList
| Feature | Array | ArrayList |
|---|
Cheat Sheet
Quick syntax
// Declare
int[] numbers;
// Create with size
numbers = new int[5];
// Declare and create
int[] numbers2 = new int[5];
// Initialize with values
int[] numbers3 = {1, 2, 3};
// Initialize with explicit new
int[] numbers4 = new int[]{1, 2, 3};
Access and update
System.out.println(numbers3[0]);
numbers3[1] = 99;
Useful rules
- Arrays store values of the same type
- Array indexes start at 0
- Use
.lengthto get the size - Arrays in Java have fixed size
new int[3]gives default values:[0, 0, 0]new String[3]gives default values:
FAQ
What is the difference between declaring and initializing an array in Java?
Declaring creates a variable that can refer to an array. Initializing usually means creating the array and possibly giving it values.
How do I create an array with default values in Java?
Use new with a size, for example:
int[] numbers = new int[4];
Java fills it with default values.
How do I initialize an array with values in Java?
Use curly braces when declaring:
int[] numbers = {1, 2, 3};
Can I assign {1, 2, 3} to an array after declaration?
Not by itself. After declaration, use:
numbers = new int[]{1, 2, 3};
Are Java arrays fixed in size?
Yes. Once created, the length cannot change.
How do I find the size of an array in Java?
Use the length field:
Mini Project
Description
Create a simple Java program that stores and prints a week's temperatures using an array. This project helps you practice declaring an array, creating it with a fixed size, assigning values by index, and reading values back.
Goal
Build a program that creates an array, fills it with values, and prints each value along with the array length.
Requirements
- Declare a
doublearray for 7 temperatures. - Initialize the array with a size of 7.
- Assign a temperature to each index from
0to6. - Print the total number of temperatures using
.length. - Print each temperature on its own line.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.