Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Arrays in Java

Declare and initialize arrays

In Java, an array is a fixed-size data structure that holds multiple values of the same type. There are different ways to declare and initialize an array.

Declaration of an Array

Before using an array, it must be declared. The syntax is:


dataType[] arrayName;  // Recommended syntax
// OR
dataType arrayName[];  // Valid but less preferred

Example:


int[] numbers;  // Declaring an integer array
String[] names; // Declaring a string array

At this stage, the array is just declared but not initialized.

Initializing an Array

After declaring an array, we must allocate memory for it. There are multiple ways to do this:

a) Using the new Keyword (Fixed Size)


int[] numbers = new int[5]; // Creates an array of size 5 with default values (0)

The array size must be specified while using new.

b) Declaring and Assigning Values Directly


int[] numbers = {10, 20, 30, 40, 50}; // Size is automatically determined
String[] names = {"Alice", "Bob", "Charlie"};

This method is preferred when we already know the values.

c) Initializing with a Loop (Dynamic Values)


int[] numbers = new int[5]; // Array of size 5
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 10; // Assigning values dynamically
}

This method is useful when we generate values at runtime.

Example Program: Declare and Initialize an Array


public class MasterBackend {
    public static void main(String[] args) {
        // Declaration and initialization
        int[] ages = {18, 20, 22, 24, 26};

        // Printing array elements
        System.out.println("Ages of students:");
        for (int i = 0; i < ages.length; i++) {
            System.out.println("Student " + (i + 1) + ": " + ages[i]);
        }
    }
}

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board