Arrays in Java Tutorial: how to declare & initialize Java arrays

Nov 11, 2020 - 10 min read
Amanda Fawcett

Java remains one of the world’s most popular and used programming languages due to its platform independence. Many new developers learn Java as their first language. Java is known for being verbose, and some developers struggle to get the basics down.

Understanding data structures is a key component to Java programming, and arrays are the first step. To help your Java journey, in this tutorial, we will learn how to implement and use arrays in Java. A Java array is a group of similarly-typed variables that use a shared name.

Today, we will learn what’s unique about arrays in Java syntax and explore how to declare, initialize, and operate on array elements.

Today we will learn:

Your definitive guide to Java programming

In this course, you learn all the important concepts of Java, from programming paradigms to objects, algorithms, arrays, and beyond. All with hands-on exercises.

A Complete Guide to Java Programming

What are arrays in Java?

A variable is a location in our program with a name and value. This value could be any data type, like int. An array is another variable type or a container object with a fixed number of values that are all of a single type. In other words, a collection of similar data types. When an array is created, that size of the array (or length) is also fixed.

Simplified: Think of a Java array as a box with many compartments, and inside each compartment is one value

An array of 5 elements with the index starting from 0
An array of 5 elements with the index starting from 0

The compartments in the box must remain ordered using indexing. Array elements are indexed, and each index should point to an element. It will look something like this:

INDICES => index 0->index 1->index 2->index 3->...index n

ELEMENTS => element 1->element 2->element 3->element 4->....element n+1

Each compartment has a numerical index that we use to access a value. An array index always begins with 0. So, say we have 10 compartments in an array container box. There will be 10 indices, but they start from 0 and end at 9, because the index 0 points to the first element 1.


What’s unique about arrays in Java?

Arrays in every language will differ slightly. Here are the unique qualities of arrays in Java that differ from other languages you may use, like C or C++.

  • Arrays are dynamically allocated
  • Arrays are objects in Java
  • A Java array variable is declared like other variables
  • The variables are ordered, with the index beginning at 0
  • The superclass of the array type is Object
  • The size of an array is specified with an int value

Types of arrays in Java

In Java, there are a few different types of arrays that we can work with.

A single dimensional array is a normal array that you will use most often. This type of array contains sequential elements that are of the same type, such as a list of integers.

int[] myArray = {10, 20, 30, 40}

A multidimensional array is an array of arrays. A two dimensional array is an array made up of multiple one dimensional arrays. A three dimensional array is an array made up of multiple two dimensional arrays.

// Two dimmensional array
int[][] a = new int[3][4];

// Three dimmensional array
String[][][] data = new String[3][4][2];

An array of objects is created just like an array of primitive data types.

Student[] arr = new Student[4]; 

//This is a user-defined class

The ArrayList is a class class that is a resizable array. While built-in arrays have a fixed size, ArrayLists can change their size dynamically, so the elements of the array can be added and removed using methods, much like vectors in C++.

Note: This is in the the java.util package.

import java.util.ArrayList; //import the ArrayList class

class MyClass {

    public static void main( String args[] ) {

    ArrayList<String> shapes = new ArrayList<String>(); // Create an ArrayList object with a string data type



Declaring an array in Java

Now that we know the types of arrays we can use, let’s learn how to declare a new array in Java. Here is the basic syntax for array declaration.

dataType[] arrayName;
  • dataType: this can be any Java object or primitive data type (such as int, byte, char, boolean, etc.)
  • arrayName: this is an identifier so you can access the array

Let’s create a simple array in Java to understand the syntax. First, declare the variable type using square brackets [].

String[] dogs;

Now we have a variable that holds an array of strings. We can insert values using an array literal. We place our values in a list separated by commas that is held within curly brackets {}.

String[] dogs = {"Pitbull", "Poodle", "Lab", "Pug"};

It looks a little different to create an array of integers.

int[] myNum = {5, 10, 15, 20};

As we learned, arrays have a fixed amount of elements. We have to define the number of elements that our array will hold to allocate memor. Here’s the basic syntax for memory allocation.

// declaring an array 
double[] data; 

// allocating memory 
data = new Double[5];

Above, the array can store 5 elements, meaning the the length of the array is 5. For another example, say we want to store the names of 50 people. We create an array of the string type. The array below can only store up to 50 elements.

String[] array = new String[50];

There are other ways to declare an array in Java. Here are the three options:

  • int[] myNumberCollection = new int[5];
  • int[] myNumberCollection; myNumberCollection = new int[5];
  • int[] myNumberCollection = {1, 2, 56, 57, 23};

In the first two cases, we add elements to the array container manually. In the third case, we added the elements when we declared the array.

// initializing first element

    myNumberCollection[0] = 1;

// initializing second element

    myNumberCollection[1] = 2;

Note: In Java, it is recommended in the official documentation to declare an array using:

public static void main(String[] args){}.

Initializing an array in Java

In Java, we can initialize arrays during declaration. In Java, initialization occurs when you assign data to a variable. Declaration is just when you create a variable. So, when you first create a variable, you are declaring it but not necessarily initializing it yet.

Here is how we can initialize our values in Java:

//declare and initialize an array

int[] age = {25, 50, 23, 21};

Above, we created an array called age and initialized it with the values we wanted to add. Here, we did not declare the size of the array because the Java compiler automatically counts the size.

We can also initialize arrays using the index number, like below:

// declare an array 

int[] age = new int[5]; 

// initialize array 

age[0] = 25; 

age[1] = 50; 


Accessing and changing elements of an array

We access the element of an array using its index number. As we discussed before, the index begins with 0 and ends at total array size minus one. If you want to access all the elements of array, you can use a forLoop.

Below is the syntax for accessing elements of an array:

// access array elements

Let’s continue our dogs example from before. Below, we want to access the first value and print the result.

class Main {
 public static void main(String[] args) {
   // create an array
   String[] dogs = {"Pitbull", "Poodle", "Lab", "Pug"};

   // access first element 
   System.out.println("First Element: " + dogs[0]);


Note: In Java, you can use System.out.println to print a value.

We can also change the value of an element using its index number. Using our example above, say we want to change Pitbull to Terrier.

class Main {
 public static void main(String[] args) {
    String[] dogs = {"Pitbull", "Poodle", "Lab", "Pug"};
    System.out.println("Before update" + dogs[0]); // print old value

    dogs[0] = "Terrier"; // changing value

    System.out.println("After update" + dogs[0]); // print new value


Become a Java developer

Learn Java without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient. You can even earn a certificate to add to your resume.

A Complete Guide to Java Programming

Looping through array elements

We can also loop through each element of the array. In Java, there are multiple ways to loop over an array, such a for loop, enhanced for loop, while loop, or do-while loop.

The traditional loop allows you to iterate until you reach the last element. Enhanced for loops allow you to iterate without dealing with counts.

Instead of printing each element, you can use a for Loop to iterate the index. It will start at 0 and traverse the length of the array.

Let’s look at an example of a for loop to see how it works in Java. Below, we use the Java for Loop to iterate through each array element. We use the length property to get the size of our array.

class Main {
 public static void main(String[] args) {
   // create an array
   int[] age = {3, 2, 7, 8};

   // loop through the array with for Loop
   System.out.println("Using for Loop:");
   for(int i = 0; i < age.length; i++) {

Note: For-loops in Java are identical to C and Javascript.

Common Java array operations

Once we create and initialize our arrays, we need to learn how to maniplate and use them. There is a lot we can do with arrays in Java. These kinds of operations are very common questions in coding interviews. Here are examples of some of the operations you can do on Java arrays.

Get the first and last element

This is one of the most common tasks we can do with Java arrays due to its index-based organization. First, we declare and initialize an int array.

Then we use the index value 0 and length attribute to get specific elements.

class Main {
 public static void main(String[] args) {
     int[] array = new int[] { 1, 2, 3, 4, 5, 6 };

     int firstItem = array[0];

int lastItem = array[array.length - 1];


Add a new item to an Array

Since arrays hold a fixed size of values, we cannot add items that exceed the limit. Instead, we can declare a larger array and copy the elements of the smaller array into it. The Arrays class has a method to replicate the values of an array for this purpose.

int[] newArray = Arrays.copyOf(array, array.length + 1);

newArray[newArray.length - 1] = newItem;

Covert a list to an array

There are two variants of this method:

  1. toArray(): This method returns an array of type Object[] whose elements are all in the same sequence as they are in the list. Casting is used to specify each element’s type when performing some operations.
import java.util.ArrayList;

public class ListToArray {

	public static void main(String[] args) {
		// A list of size 4 which is to be converted:
		ArrayList<Integer> list = new ArrayList<>();
		// ArrayList converted to Object[] array:
		Object[] objArr = list.toArray();
		for(Object obj: objArr){
      // Using casting before performing addition:
      System.out.println((Integer)obj + 1);

  1. toArray(T[] arr): This variant takes an already defined array as its parameter. When the array’s size is greater than or equal to the size of the list, then the array is filled with the elements of the list. Since the type of the returned array is specified by the parameter’s type, casting is unnecessary.
import java.util.ArrayList;

public class ListToArray {

	public static void main(String[] args) {
    // A list of size 4 to be converted:
		ArrayList<Integer> list = new ArrayList<>();
    // Declaring an array of size 4:
		Integer[] arr = new Integer[4];
    // Passing the declared array as the parameter:
    // Printing all elements of the array:
    System.out.println("Printing 'arr':");
		for(Integer i: arr)

    // Declaring another array of insufficient size:
    Integer[] arr2 = new Integer[3];

    // Passing the array as the parameter:
    Integer[] arr3 = list.toArray(arr2);

    // Printing the passed array:
    System.out.println("\n'arr2' isn't filled because it is small in size:");
    for(Integer i: arr2)
    // Printing the newly allocated array:
    System.out.println("\n'arr3' references the newly allocated array:");
    for(Integer i: arr3)

Get a random value

We can use the objectjava.util.Random, we can access a random value.

int anyValue = array[new Random().nextInt(array.length)];

Insert a Value Between two other Values

Inserting an item in an array between two others is somewhat tricky. The class ArrayUtils was created to make this possible. Here, we specify the index where we want to insert the value. Our the output is a new array with our now larger number of elements.

int[] largerArray = ArrayUtils.insert(2, array, 77);

Check if an Array Is Empty

We can use the length attribute of arrays to check if it is empty or not.

boolean isEmpty = array == null || array.length == 0;

The ArrayUtils helper class also offers a null-safe method for this process, but this function depends on the length of the data structure.

boolean isEmpty = ArrayUtils.isEmpty(array);

What to learn next

Congrats! You should now have a good idea of how arrays work in Java. There is still more to learn! There are so many more array operations that we can perform, and many of these are asked during coding interviews. Take a look at this list to get an idea of what to learn next:

  • Copy an array in Java
  • Box and unbox an array
  • Shuffle elements of an array
  • Find the Min and Max in an array with Java
  • Remove the first element of an array
  • Find the sum and average of a Java array
  • Invert an array in Java

The best way to learn Java is through hands on practice. Check out Educative’s definitive Java course A Complete Guide to Java Programming to continue learning these operations and beyond. You’ll start with the fundamentals of programming and move on to iterative constructs, useful algorithms, and data structures.

This course will get you on the fast track to becoming a proficient and modern Java developer. You can even earn a certificate to add to your resume!

Happy learning!

Continue reading about Java

WRITTEN BYAmanda Fawcett

Join a community of 270,000 monthly readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.