Java Array
In Java, an array is an object that stores multiple values of the same data type in a fixed-length, index-based structure. Once an array is created, its length cannot be increased or decreased, but the values stored at existing indexes can be read and updated.
Arrays are useful when you need to keep related values together, such as marks of students, names in a list, numbers to process in a loop, or objects returned from a method. Java arrays use zero-based indexing: the first element is at index 0, the second element is at index 1, and so on.
For example, an array of integers assigned to a variable arr is
int arr[] = {2, 4, 6};
An array of strings is
String arr[] = {"apple", "banana", "cherry"};
Java Array Tutorials by Task
The following Java array tutorials cover declaration, initialization, traversal, checks, transformations, and common programs. Use them when you need a focused example for a specific array operation.
Java Array Basics: Declaration, Length, and Array Types
- Java – Initialize Array
- Java – Initialize String Array
- Java – Define String Array of Specific Size
- Java – Array Length
- Java – Array of Integers
- Java – Array of Strings
- Java – Array of Objects
- Java – Array of Arrays
- Java – Append to Array
- Java – Find Index of Element in Array
Java Array Iteration: while Loop, for Loop, and for-each Loop
- Java – Iterate over Array Elements
- Java – Iterate over Array using While Loop
- Java – Iterate over Array using For Loop
- Java – Iterate over Array using ForEach
- Java – Iterate over String Array
Java Array Checks: Empty Array, Contains, and Array Equality
- Java – Check if Array is Empty
- Java – Check if Array contains Specific Element
- Java – Check if Two Arrays are Equal
Java Array Transformations: Add, Remove, Slice, Reverse, Join, and Sort
- Java – Add an Element to Ending of Array
- Java – Add an Element to Starting of Array
- Java – Concatenate Arrays
- Java – Convert Array to String
- Java – Join Elements of String Array with Delimiter
- Java – Reverse an Array
- Java – Remove First Element of Array
- Java – Remove Last Element of Array
- Java – Slice an Array
- Java – Sort Integer Array
- Java – Sort an Array only in Specific Index Range
- Java – Sort String Array
Java Array Example Programs: Print, Sum, Average, Smallest, and Largest
- Java – Print Elements of Array
- Java – Find Sum of Elements in Array
- Java – Find Average of Elements in Array
- Java – Find Smallest Number of an Array
- Java – Find Largest Number of an Array
How Java Arrays Work
A Java array has three important properties:
- Same element type: an
int[]storesintvalues, aString[]storesStringreferences, and so on. - Fixed length: the number of elements is decided when the array object is created.
- Index-based access: every element is accessed using an integer index from
0toarrayName.length - 1.
Do not describe a Java array as immutable. The array length is fixed, but individual elements can be modified. For example, numbers[2] = 50; changes the value at index 2 if the index is valid.
Java Array Declaration Syntax
The syntax to declare an Array is
datatype arrayName[];
Please observe the placement of square brackets, right after the array name. We can also place the square brackets right after datatype as shown in the following.
datatype[] arrayName;
We can use any of these two notations.
So, to define an integer array, we would write a statement as shown below.
int numbers[];
//or
int[] numbers;
When you declare an array, we are only reserving the variable name and notifying the compiler that we are going to use this variable name to store elements of this particular datatype.
In Java code, int[] numbers; is generally preferred because it clearly says that the variable type is “array of int”. The form int numbers[]; is also valid Java syntax.
Java Array Initialization with a Fixed Size
To initialize an array, we can assign the array variable with new array of specific size as shown below.
arrayName = new datatype[size];
We have to mention the size of array during initialization. This will create an array in memory, with all elements initialized to their corresponding static default value.
In the following program, we initialized an integer array with a size of 10.
Main.java
public class Main {
public static void main(String[] args) {
int numbers[];
numbers = new int[10];
}
}
We have first declared the variable and then initialized it. Of course, we have declared and initialized the array in two different statements. But you can combine the declaration and initialization, to form the definition of array, as shown below.
Main.java
public class Main {
public static void main(String[] args) {
int numbers[] = new int[10];
}
}
In the above example, we have created an integer array named numbers, and initialized it to an integer array of size 10 with default values. The default value for an integer is 0.
Java Array Default Values
When an array is created with new, Java assigns a default value to each element. The default value depends on the array element type.
| Java array type | Default element value |
|---|---|
byte[], short[], int[], long[] | 0 for the corresponding numeric type |
float[], double[] | 0.0 for the corresponding floating-point type |
char[] | '\u0000' |
boolean[] | false |
Reference type arrays such as String[] | null |
This is why reading from a newly created int[] returns 0 until you assign another value to that index.
Java Array Literal Initialization with Elements
You can also assign elements directly to the array when declaring it.
In the following example, we have declared and initialized array with elements.
Main.java
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
}
}
Now numbers is an integer array with size of 5, because there are five elements in the array we assigned.
The size of array is fixed. You can only modify the existing elements of the array. But you cannot remove elements or add elements to the array.
If you need a collection that grows and shrinks frequently, use ArrayList instead of a plain array. If you need a compact fixed-size structure and you know the number of values in advance, an array is often suitable.
How to Access Java Array Elements?
Now that we have initialized an array with elements, how can we access them? Array elements can be accessed using index. Index is the position of the element from starting of the array. The first element has an index of 0, second element has an index of 1, third element has an index of 2 and so on.
Following is the syntax to access an element of array.
arrayName[index]
The above statement can be used either to read an element at given index, or set an element at given index. The read or write operation depends on which side of assignment operator you are placing this.
For example, in the following program, we are reading the element of array nums at index 4.
Main.java
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10, 12, 14, 16};
int n = numbers[4];
System.out.println("Element at index=4 is : " + n);
}
}
Output
Element at index=4 is : 10
And in the following example, we are updating the element of array at index 4.
Main.java
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10, 12, 14, 16};
numbers[4] = 25;
int n = numbers[4];
System.out.println("Element at index=4 is : " + n);
}
}
Output
Element at index=4 is : 25
From these examples, remember the valid index range. If an array has length n, the valid indexes are from 0 to n - 1. Accessing an index outside this range throws ArrayIndexOutOfBoundsException at runtime.
Java Array Length and Valid Index Range
Use the length field to get the number of elements in a Java array. It is not a method, so write numbers.length, not numbers.length().
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
System.out.println("Array length: " + numbers.length);
System.out.println("Last element: " + numbers[numbers.length - 1]);
}
}
Array length: 5
Last element: 10
The expression numbers[numbers.length - 1] is commonly used to access the last element of a non-empty array.
How to Iterate Over Java Array Elements
Now, how do we access elements of an array one by one in a loop? Java has looping statements like while loop, for loop and advanced for loop. We can use any of these looping statements to iterate over elements of a Java Array.
In the following example, we have initialize a Java Array, and iterate over elements of Array using Java For Loop.
Main.java
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
for (int index=0; index < numbers.length; index++) {
System.out.println(numbers[index]);
}
}
}
Output
2
4
6
8
10
Use a normal for loop when you need the index. Use the enhanced for loop when you only need each element value.
public class Main {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
apple
banana
cherry
Useful java.util.Arrays Methods for Java Arrays
The java.util.Arrays class provides utility methods for common array tasks such as printing, sorting, copying, filling, searching, and comparing arrays. It is part of the Java standard library.
| Method | Common use |
|---|---|
Arrays.toString(array) | Convert a one-dimensional array to a readable string. |
Arrays.sort(array) | Sort array elements into natural order. |
Arrays.copyOf(array, newLength) | Create a copied array with the requested length. |
Arrays.equals(a, b) | Check whether two arrays have the same elements in the same order. |
Arrays.fill(array, value) | Set every element of an array to the same value. |
The following example prints and sorts an integer array using Arrays.toString() and Arrays.sort().
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {8, 2, 10, 4};
System.out.println("Before sorting: " + Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println("After sorting: " + Arrays.toString(numbers));
}
}
Before sorting: [8, 2, 10, 4]
After sorting: [2, 4, 8, 10]
For official reference, see the Java language tutorial page on arrays and the java.util.Arrays API documentation.
Common Java Array Mistakes to Avoid
- Using index 1 for the first element: Java arrays start at index
0. - Using
length()on an array: arrays uselength, while strings uselength(). - Trying to add elements directly: a Java array has fixed length; create a new array or use
ArrayListfor a resizable collection. - Comparing arrays with
==: this checks whether two array variables refer to the same array object. UseArrays.equals()to compare contents. - Reading from a reference array before assigning objects: elements of arrays such as
String[]arenullby default.
Java Array FAQ
What are the uses of arrays in Java?
Arrays are used to store a fixed number of related values of the same type. For example, you can use an array to store marks, prices, names, characters, matrix rows, or object references that must be processed together.
How to declare an array in Java?
You can declare an array by placing square brackets after the data type or after the variable name. The commonly preferred form is int[] numbers;. The form int numbers[]; is also valid.
How to initialize an array in Java?
You can initialize an array with a fixed size using new, such as int[] numbers = new int[5];. You can also initialize it with values directly, such as int[] numbers = {2, 4, 6};.
How to access elements in a Java array?
Use the array name followed by the index in square brackets. For example, numbers[0] accesses the first element and numbers[numbers.length - 1] accesses the last element of a non-empty array.
Can the length of a Java array be changed?
No. Once a Java array object is created, its length cannot be changed. You can update existing elements, create a new array with a different length, or use a resizable collection such as ArrayList.
Java Arrays Editorial QA Checklist
- Check that every Java array example uses zero-based indexing correctly.
- Verify that array length is described as fixed, while array element values are described as mutable.
- Confirm that examples use
array.lengthfor arrays and do not usearray.length(). - Ensure every program output matches the Java code shown immediately above it.
- Review all code blocks so Java examples use
language-java, syntax demonstrations uselanguage-java syntax, and new output blocks useoutput.
Conclusion: Java Arrays in Practice
In this Java Tutorial, we learned about Java Arrays and different concepts related to them with detailed tutorials and examples. A Java array is best used when the element type is known, the length is fixed, and index-based access is needed. For tasks that require frequent insertion or deletion, consider a collection class such as ArrayList.
TutorialKart.com