Explain Codes LogoExplain Codes Logo

How to initialize an array in Java?

java
array-initialization
java-arrays
programming-concepts
Nikita BarsukovbyNikita Barsukov·Oct 15, 2024
TLDR

Create and populate a Java array on-the-fly: int[] arr = {1, 2, 3, 4, 5}; Or, if you need an empty array with a fixed size: int[] arr = new int[5];

In the realm of Java arrays, size and type matter a lot. Remember that in Java, arrays once created, acquire a fixed size and the type of values you put in needs to synchronize with the declared array type. As for instantiating, if the array values are known upfront, use the curly brace initializer, else use the new keyword and specify the size.

Let's delve deeper into good practices and common mistakes:

  • Match the element type with the array's declared data type to avoid compilation failures.
  • Use .length property to get the size of array and avoid falling into ArrayIndexOutOfBoundsException pit.
  • Java array indices start at zero, hence the first element will be at index 0.
  • Utilize the array initializer syntax when you know the array contents while creating, it aids in making your code lean and more efficient.

Initialization styles and common trip-ups

1. Declaration and Initialization style: Empty Arrays

To declare an array which will be filled later: String[] days = new String[7];

Trip-up #1: Arriving at the Wrong Station, Index out of bounds

Avoid:

int[] numbers = new int[3]; numbers[3] = 4; // Oops! This train doesn't go to station 3.

Correct:

int[] numbers = new int[3]; numbers[2] = 4; // Yes Captain! Last Index in a size 3 array is 2.

2. Declaration and Initialization style: Pre-filled Arrays

If you already know the rail stops (array elements): double[] temperatures = {98.6, 99.5, 97.1};

Trip-up #2: Boarding the Wrong train, Type mismatch

Avoid:

int[] primeNumbers = {2, 3.7, 5, 7}; // Oops! train 3.7 doesn't stop at "int" stations.

Correct:

int[] primeNumbers = {2, 3, 5, 7}; // All aboard! All elements are "int" trains.

Advanced conventions of array initialization

Array Initialization through looping

char[] grades = new char[5]; for (int i = 0; i < grades.length; i++) { grades[i] = getGrade(i); // getGrade(): The grade vending machine }

Array duplication and operations

Java's System.arraycopy method takes the wheel when you want to copy an existing array into a new one.

System.arraycopy(sourceTrain, 0, destinationTrain, 0, sourceTrain.length); // All aboard, please mind the gap!

Multidimensional arrays

Initialize at the time of declaration:

int[][] 2DMatrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Or use loops for dynamic assignments:

int[][] 2DMatrix = new int[3][3]; for (int i = 0; i < 2DMatrix.length; i++) { for (int j = 0; j < 2DMatrix[i].length; j++) { 2DMatrix[i][j] = i * j; // Just some random multiplication for demo. } }

Wise usage of Java 8 and above features (the fancy city trains!)

Java 8 introduced streams, which can also be used for array initialization:

String[] stringArray = Stream.of("a", "b", "c", "d").toArray(String[]::new);

Visualization

Think of array initialization in Java as setting up a bookshelf for your books:

Empty Bookshelf (📚): [ , , , ]

Initialization with specific size but no books yet:

Book[] bookShelf = new Book[4]; // A bookshelf with space for 4 books
Empty Bookshelf (📚): [_, _, _, _]

Filling in the books (array elements):

bookShelf[0] = new Book("Java Fundamentals"); bookShelf[1] = new Book("Effective Java"); bookShelf[2] = new Book("Spring in Action"); bookShelf[3] = new Book("Clean Code");
Filled Bookshelf (📚): [📘, 📗, 📙, 📕]

This is exactly like organizing your precious book collection on a shelf!