Explain Codes LogoExplain Codes Logo

How do I declare and initialize an array in Java?

java
array-declaration
array-initialization
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 16, 2024
TLDR

Here's how to create a single-dimensional array:

int[] arraySingle = {1, 2, 3, 4, 5}; // Because who needs six numbers, right?

Need an empty array? Specify the size with new:

int[] arrayEmpty = new int[5]; // Noah's Ark for zeros.

Creating a two-dimensional array? Piece of cake:

int[][] arrayMulti = {{1, 2}, {3, 4}}; //Good old 2x2. Tic Tac Toe anyone?

If you prefer your multidimensional array uninitialized:

int[][] arrayInit = new int[2][2]; // Zeros are people too.

Remember, arrays in Java are indexed from 0, and their size is immutable once initialized.

Create an Array with Specific Numbers

You can populate your array with a sequence of numbers. All Hail IntStream :

int[] startFromZero = IntStream.range(0, 10).toArray(); // Because the world started counting from zero.

Need an inclusive range ?

int[] inclusive = IntStream.rangeClosed(1, 10).toArray(); // We like everyone.

For our selective folks, here's you can add specific values into an array :

int[] choosy = IntStream.of(12, 34, 56).toArray(); // Pick and mix.

Some people like it sorted, well here you go:

int[] sorted = IntStream.of(12, 9, 21).sorted().toArray(); // Neat freaks got their cover.

The Matrix Revisited: Multidimensional Arrays

Creating a two-dimensional array is easier than you think:

int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Who needs effects when you can have Matrix in console?

If your sub-arrays fancy different sizes, make it a ragged array:

int[][] raggedArray = { {1, 2}, {3, 4, 5}, {6, 7, 8, 9} }; // When sub-arrays can't agree on sizes...

Shake it up: Common Operations and Utilities

The java.util.Arrays class is your Swiss army knife. Want to fill the array but too lazy to type:

Arrays.fill(myArray, 42); // When you're feeling 42ish.

Clone wars? Here's how to copy arrays:

int[] cloneArmy = Arrays.copyOf(originalArray, newLength); // Originality is overrated anyway.

Are these twins or mirror images? Compare arrays:

boolean dittoMove = Arrays.equals(arr1, arr2); // Pokémon reference

And to talk your array into being a string:

String arrayInDisguise = Arrays.toString(myIntArray); // Array's undercover mission.

Syntax Surfers

Java caters to your syntax preferences. Fancy cursive or print, it got you:

int[] arraySyntax1; // More in vogue int arraySyntax2[]; // Throwback to the C era

Array Declaring and Initializing: Best Practices

When declaring the size of an array, remember it's also the max number of elements it can hold. Also, over-declaring sizes may result in wasting memory. Happy Earth day:

int[] overkillArray = new int[100]; // Too much of anything is bad.

Initializing with values is the speed racer way but may lead to scalability issues:

int[] fixedArray = {1, 2, 3}; // Manual labor in the age of automation!

The separate declaration and initialization waltz can lead to code clarity. Especially in areas with fat codebases:

int[] array; // Sailors preparing the ship // Monster octopus in the sea aka lot of code array = new int[] {3, 6, 9}; // Cannonballs loaded, fire!