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 new with explicit values
int[] numbers = new int[]{1, 2, 3, 4, 5};
This form is useful in places where Java requires an expression.
Example with strings
String[] names = {"Ana", "Ben", "Chris"};
This creates an array of String values.
Accessing elements
int[] numbers = {10, 20, 30};
System.out.println(numbers[0]); // 10
System.out.println(numbers[1]); // 20
Updating elements
int[] numbers = new int[3];
numbers[0] = 99;
numbers[1] = 88;
numbers[2] = 77;
Each position can be assigned a value using its index.
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
-
numbers[2] = 30;- The third element becomes
30.
- The third element becomes
-
System.out.println(numbers[1]);- Java reads the value at index
1. - That value is
20. - Output:
- Java reads the value at index
20
Array state after each assignment
| Step | Array contents |
|---|---|
| After creation | [0, 0, 0] |
After numbers[0] = 10 | [10, 0, 0] |
After numbers[1] = 20 | [10, 20, 0] |
After numbers[2] = 30 | [10, 20, 30] |
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) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
Arrays are often passed into methods for processing.
Configuration-like lists
String[] allowedRoles = {"ADMIN", "EDITOR", "VIEWER"};
This can be useful for fixed sets of values, though in larger systems other structures may also be used.
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:
int[] numbers = new int[3];
numbers[2] = 40;
3. Confusing size with last index
For an array of size 5:
- length is
5 - last index is
4
4. Mixing types
Broken code:
int[] numbers = {1, 2, "three"};
Problem:
- An
intarray can only contain integers.
5. Using braces incorrectly after declaration
Broken code:
int[] numbers;
numbers = {1, 2, 3};
Problem:
- This syntax only works at the point of declaration.
Fix:
int[] numbers;
numbers = new int[]{1, 2, 3};
6. Forgetting that arrays have fixed size
Once created, you cannot make an array longer or shorter. If you need dynamic resizing, developers often use ArrayList instead.
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 |
|---|---|---|
| Size | Fixed | Dynamic |
| Stores primitives directly | Yes | No, uses wrapper types like Integer |
| Syntax | Simple | Requires class usage |
| Best for | Fixed-size data | Data that grows or shrinks |
Regular for loop vs enhanced for loop
| Loop type | Best when |
|---|---|
for (int i = 0; i < arr.length; i++) | You need the index |
for (int value : arr) | You only need each value |
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:[null, null, null]
Common defaults
| Type | Default value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
Object types like String | null |
Remember
- Size 3 means valid indexes are
0to2 - Use
new int[]{...}if assigning values after declaration
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:
System.out.println(numbers.length);
Can an array store different data types in Java?
No, a normal Java array stores one type only, such as all int values or all String values.
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
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
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.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.