Java Arrays: Declaring, Initializing, for-each Loops and Copying
One-dimensional Java arrays: declaring and creating arrays, initializers and anonymous arrays, default values, indexes and ArrayIndexOutOfBoundsException, the enhanced for-each loop, printing with Arrays.toString, reference vs. value copying with Arrays.copyOf, and command-line arguments.
kvi5hnuCode Sprout team member10 min readOn this page
So far, every variable has held a single value. Many programs need to work with a sequence of values: test scores, the days of a month, the pixels of an image. An array holds a fixed number of values of the same type, each accessed by an integer index.
Arrays are the most basic data structure in Java. The more flexible ArrayList (covered in the inheritance part) and the collections framework are built on top of them.
Declaring and Creating Arrays
An array type is written as the element type followed by []. Declaring a variable of that type:
int[] a;
This only declares the variable. No array exists yet. Create one with the new operator, giving the length:
int[] a = new int[100]; // an array of 100 ints
var b = new int[100]; // same, with type inference

Important facts:
- The length doesn't have to be a constant:
new int[n]creates an array of lengthn, computed at runtime. - Once created, an array's length can never change. You can change its elements, but not add or remove slots. If you need a sequence that grows and shrinks, use an
ArrayList. - The length isn't part of the type. The variable
ahas typeint[]and can refer to anintarray of any length. - An array is an object. The variable holds a reference to it, which matters when you copy arrays (see below).
Array Initializers
When you know the values in advance, an array initializer creates and fills the array in one step, without new or a length:
int[] evens = { 2, 4, 6, 8, 10, 12 };
The length is the number of values (6 here). A trailing comma after the last value is allowed, which is convenient for lists that grow over time:
String[] authors = {
"James Gosling",
"Bill Joy",
"Guy Steele",
// add more names here, each followed by a comma
};
Anonymous arrays
The form new int[] { … } creates an array without a variable. You can use it wherever an array is expected, for example to give an existing variable new contents, or to pass an array to a method:
evens = new int[] { 14, 16, 18, 20, 22, 24 };
It's shorthand for:
int[] anonymous = { 14, 16, 18, 20, 22, 24 };
evens = anonymous;
The short { … } form only works in a declaration. Assigning to an existing variable needs new int[] { … }.
Empty arrays
Arrays of length 0 are legal and useful, for instance as the result of a method that found nothing:
int[] none = new int[0];
String[] noNames = new String[] {};
An empty array is not the same as null. none.length is 0, and you can loop over it safely (the loop body simply never runs), whereas any access through a null reference throws a NullPointerException. Returning an empty array instead of null saves callers from having to check.
Accessing Elements
Elements are numbered from 0. In an array of length n, the valid indexes are 0 to n − 1. Use square brackets to read or write an element:
int[] squares = new int[20];
for (int i = 0; i < 20; i++) {
squares[i] = i * i; // 0, 1, 4, 9, ..., 361
}
array.length gives the number of elements. Note that it's a field, written without parentheses, unlike String's length() method. Use it instead of hard-coding the length:
for (int i = 0; i < squares.length; i++) {
System.out.println(squares[i]);
}
Accessing an index outside 0 … length - 1 throws an ArrayIndexOutOfBoundsException:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Java always checks array bounds. A program can never silently read or overwrite memory outside an array, which is a common source of crashes and security holes in C and C++.
Default values
A newly created array is filled with default values:
| Element type | Default |
|---|---|
int, long, short, byte, double, float | 0 / 0.0 |
char | '\u0000' (the "null character", code 0) |
boolean | false |
object types (String, …) | null |
The last row surprises beginners. new String[10] creates an array of ten null references, not ten empty strings. Calling a method on an element, say names[0].length(), throws a NullPointerException. Fill the array first if you need actual strings:
String[] names = new String[10];
for (int i = 0; i < names.length; i++) {
names[i] = "";
}
(Arrays.fill(names, "") does the same in one line.)
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int[] a = new int[5];
for (int i = 0; i < a.length; i++) {
a[i] = i * i;
}
System.out.println(Arrays.toString(a) + " length " + a.length);
String[] authors = { "James Gosling", "Bill Joy", "Guy Steele", };
System.out.println(authors.length + " " + authors[authors.length - 1]);
double[] d = new double[3];
boolean[] flags = new boolean[2];
String[] names = new String[3];
System.out.println(Arrays.toString(d) + Arrays.toString(flags) + Arrays.toString(names));
int[] evens = { 2, 4, 6, 8, 10, 12 };
evens = new int[] { 14, 16, 18, 20, 22, 24 };
System.out.println(Arrays.toString(evens));
int[] none = new int[0];
System.out.println(none.length + " " + Arrays.toString(none));
try {
System.out.println(a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
[0, 1, 4, 9, 16] length 5
3 Guy Steele
[0.0, 0.0, 0.0][false, false][null, null, null]
[14, 16, 18, 20, 22, 24]
0 []
Index 5 out of bounds for length 5
The Enhanced for Loop ("for each")
Very often, you want to process every element in order. The enhanced for loop does it without index bookkeeping:
for (variable : collection) statement
It sets the variable to each element in turn and runs the statement. Read it as "for each element in a":
for (int element : a) {
System.out.println(element);
}
The collection must be an array or an object that implements the Iterable interface, such as an ArrayList (interfaces come later). The loop is shorter than the classic version, and you can't get the start or end index wrong.
Keep in mind:
- The loop variable holds the elements, not the indexes.
- Assigning to the loop variable doesn't change the array. It only changes the local copy:
for (int x : a) x = 0;leavesauntouched. To modify elements, use a classicforloop with an index. - Use the classic
forloop when you need the index (to print positions, compare neighbours, or process only part of the array).
public class Solution {
public static void main(String[] args) {
int[] values = { 14, 16, 18, 20, 22, 24 };
int sum = 0;
for (int v : values) {
sum += v;
}
System.out.println("sum = " + sum);
for (int v : values) {
v = 0; // only changes the loop variable
}
System.out.println(values[0]);
for (int i = 0; i < values.length; i++) {
values[i] = values[i] * 2; // index loop: modifies the array
}
System.out.println(values[0]);
for (int i = 0; i < values.length; i++) {
System.out.print("[" + i + "]=" + values[i] + " ");
}
System.out.println();
}
}
sum = 114
14
28
[0]=28 [1]=32 [2]=36 [3]=40 [4]=44 [5]=48
Printing an Array
Printing an array variable directly doesn't show its contents:
System.out.println(a); // something like [I@1b6d3586
That's the array's type code ([I means "array of int") and a hash code. To see the elements, use Arrays.toString from java.util.Arrays:
System.out.println(Arrays.toString(a)); // [0, 1, 4, 9, 16]
Copying Arrays
Copying the variable: both refer to the same array
Because array variables hold references, assigning one array variable to another doesn't copy the elements. Both variables then refer to the same array:
int[] shared = evens;
shared[5] = 99; // now evens[5] is also 99

Copying the contents: Arrays.copyOf
To get an independent copy, use Arrays.copyOf:
int[] copied = Arrays.copyOf(shared, shared.length);
The second argument sets the length of the copy. Because an array can never change size, the usual way to "grow" one is to copy it into a larger array and store the copy back in the same variable:
shared = Arrays.copyOf(shared, 2 * shared.length);
Extra elements get the default value (0, false, or null). A smaller length copies only the first elements.
Other ways to copy:
| Method | Copies |
|---|---|
Arrays.copyOf(a, newLength) | the first newLength elements (padding with defaults if longer) |
Arrays.copyOfRange(a, from, to) | elements from … to - 1 |
a.clone() | a same-length copy |
System.arraycopy(src, srcPos, dest, destPos, count) | count elements into an existing array, at any position |
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int[] evens = { 2, 4, 6, 8, 10, 12 };
int[] shared = evens;
shared[5] = 99;
System.out.println(evens[5] + " " + (shared == evens));
int[] copy = Arrays.copyOf(shared, shared.length);
copy[0] = 99;
System.out.println(Arrays.toString(evens) + " " + Arrays.toString(copy));
shared = Arrays.copyOf(shared, 2 * shared.length);
System.out.println(Arrays.toString(shared));
System.out.println(Arrays.toString(Arrays.copyOf(evens, 3))
+ Arrays.toString(Arrays.copyOfRange(evens, 2, 5)));
int[] cloned = evens.clone();
System.out.println(Arrays.equals(cloned, evens) + " " + (cloned == evens));
int[] dest = new int[8];
System.arraycopy(evens, 1, dest, 2, 4);
System.out.println(Arrays.toString(dest));
}
}
99 true
[2, 4, 6, 8, 10, 99] [99, 4, 6, 8, 10, 99]
[2, 4, 6, 8, 10, 99, 0, 0, 0, 0, 0, 0]
[2, 4, 6][6, 8, 10]
true false
[0, 0, 4, 6, 8, 10, 0, 0]
Command-Line Arguments
You've written String[] args in every main method. Now you know what it is: an array of strings holding the command-line arguments.
import java.util.Arrays;
public class Greet {
public static void main(String[] args) {
String greeting = "Good morning";
if (args.length > 0 && args[0].equals("-e")) {
greeting = "Good evening";
}
// everything after the option is the audience
String[] rest = Arrays.copyOfRange(args, Math.min(1, args.length), args.length);
if (rest.length == 0) {
System.out.println(greeting + "!");
} else {
System.out.println(greeting + ", " + String.join(" ", rest) + "!");
}
}
}
Running java Greet -e dear friends fills args with:
args[0] | "-e" |
args[1] | "dear" |
args[2] | "friends" |
and the program prints:
Good evening, dear friends!
Notes:
- Arguments are split at spaces. Use quotes to pass an argument containing spaces:
java Greet -e "dear friends"givesargs[1]="dear friends". - With no arguments,
argsis an empty array (length 0), nevernull. Checkingargs.length == 0first avoids anArrayIndexOutOfBoundsExceptiononargs[0]. - Arguments are always strings. Convert numbers with
Integer.parseInt(args[0]). - In IntelliJ IDEA, set them in Run ▸ Edit Configurations ▸ Program arguments.
Common questions
Why is it array.length but string.length()?
length is a final field of every array object, built into the language. String is an ordinary class, and length() is one of its methods. Collections use yet another name, size(). It's a historical inconsistency that you simply have to remember (the IDE helps).
Can I change the size of an array?
No. You can only create a new array and copy the elements: a = Arrays.copyOf(a, newLength). If the size changes often, use an ArrayList, which does this growing for you behind the scenes.
How do I return several values from a method?
In older code you'll see arrays like return new int[] { min, max };. In modern Java, a small record is clearer: record Range(int min, int max) {} and return new Range(min, max);. The record names its components and gives you equals, hashCode and toString.
What does [I@1b6d3586 mean when I print an array?
[I is the JVM's type descriptor for int[] ([Ljava.lang.String; is String[]), and the hex number is the identity hash code. Arrays don't override toString. Use Arrays.toString(a), or Arrays.deepToString(a) for nested arrays.
Are arrays faster than ArrayList?
Slightly, especially for primitives: an int[] stores the numbers directly, while an ArrayList<Integer> stores references to boxed Integer objects. For most code the difference doesn't matter, and ArrayList is far more convenient. Use arrays for fixed-size data, performance-critical numeric code, or when an API requires them.
Summary
- An array holds a fixed number of elements of one type. Create it with
new int[n], an initializer{ 2, 3, 5 }, or an anonymous arraynew int[] { … }. - Indexes run from 0 to
length - 1;array.lengthis a field (no parentheses). Out-of-range access throwsArrayIndexOutOfBoundsException. - New arrays are filled with
0,false,'\u0000'ornull.new String[n]holds nulls, not empty strings. - The for-each loop
for (int x : a)visits every element. It can't modify the array or give you the index. - Print with
Arrays.toString(a); compare withArrays.equals(a, b). - Assigning an array variable copies the reference. Use
Arrays.copyOf,copyOfRange,cloneorSystem.arraycopyto copy the contents. main'sString[] argsholds the command-line arguments; it's empty, not null, when there are none.
Practice Questions
What's the difference between int[] a; and int[] a = new int[10];?
The first only declares a variable; no array exists, and using a before assigning it is a compile error (or a NullPointerException if a was set to null). The second also creates an array of 10 ints, all 0, and stores a reference to it in a.
What does this print? String[] s = new String[2]; System.out.println(s[0] + " " + s.length);
null 2. Object arrays start with null elements, and string concatenation turns null into the text "null".
After int[] x = {1, 2, 3}; int[] y = x; y[0] = 10;, what is x[0]? How would you make y independent?
10, because x and y refer to the same array. Use int[] y = Arrays.copyOf(x, x.length); (or x.clone()) to make an independent copy.
Why doesn't this double the array elements? for (int v : values) v = v * 2;
v is a copy of each element. Assigning to it changes only the loop variable. Use an index loop: for (int i = 0; i < values.length; i++) values[i] *= 2;.
How do you "add" a 7th element to an int array of length 6?
You can't change an array's length. Create a longer copy and assign it back: a = Arrays.copyOf(a, a.length + 1); a[6] = value;. If this happens often, use an ArrayList<Integer> instead.
A program run as java Sum 3 4 should print 7. Write its main method.
public static void main(String[] args) {
int sum = 0;
for (String arg : args) {
sum += Integer.parseInt(arg);
}
System.out.println(sum);
}
Previous: Java BigInteger and BigDecimal: Arbitrary-Precision Arithmetic
Next: Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
Related reading
- Java Loops: while, do-while and for
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java Streams Explained: From Loops to Stream Pipelines
- Your First Java Program Explained: Classes, main, Statements and Comments

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.