Sentry Answers>Java>

How to initialize an array in Java?

How to initialize an array in Java?

Lewis D.

The ProblemJump To Solution

You want to create a new array data structure in Java, but you’re not sure how to go about it.

The Solution

In Java, the array object is used to store multiple elements of the same type. These elements are stored in contiguous memory, the length of which is immutable once initialization is complete.

We can declare an array in the same way as any other variable or object in Java, by giving a type and a name:

Click to Copy
int[] myArray;

However, this merely declares the array, it does not initialize it. The array has the value null.

Let’s take a look at the two ways we can initialize our array.

Initialize an array using known element values

If we already know the element values we want stored in the array, we can initialize the array like this:

Click to Copy
myArray = new int[]{0, 1, 2, 3};

Java allows a shorthand of this by combining declaration and initialization:

Click to Copy
int[] myArray = {0, 1, 2, 3};

This example is functionally equivalent to the previous example that declared and initialized our array separately. Interestingly, the square brackets that symbolize an array [] can be put on either side of the array name during the declaration with no change in functionality:

Click to Copy
int myArray[] = {0, 1, 2, 3};

Initialize an array using length

Next, if you do not know the exact data elements you want in your array when you initialize it, you can instead provide the length of the array, and it will be populated with default values based on the array type:

Click to Copy
int myArray[] = new int[4];

After the initialization, the array will contain the following elements.

Click to Copy
[0, 0, 0, 0]

Each data type has a default value as follows:

Data TypeDefault Values
Char‘\u0000′ which is the Unicode for null

Remember that, once the array is initialized, the length and type of the array is immutable. However, we can still make changes to the element values contained within the array.

  • Sentry BlogException Handling in Java (with Real Examples)
  • logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.