How to declare and initialize an array in Java?

By IncludeHelp Last updated : February 03, 2024

Declaring and initializing Java array

There are many ways to declare and initialize array elements in java programming, but here we are taking three different ways to do so. Here, we are writing three different ways:

Type 1

int[] arr1 = {10,20,30,40,50};

Type 2

int[] arr2;
arr2 = new int[] {100,200,300,400,500};

Type 3

int arr3[] = {11,22,33,44,55};

Efficient way to declare and initialize an array

The efficient way to declare and initialize an array is by using the following syntax:

int[] arr = new int[]{10, 20, 30};

Example to declare and initialize a Java array

This program is declaring three one dimensional integer arrays and initialising the array elements by different 3 methods.

public class Main {
  public static void main(String args[]) {
    //type 1
    int[] arr1 = {10, 20, 30, 40, 50};

    //type 2
    int[] arr2;
    arr2 = new int[] {100, 200, 300, 400, 500};

    //type 3
    int arr3[] = {11, 22, 33, 44, 55};

    //print elements
    System.out.println("Array elements of arr1: ");
    for (int i = 0; i < arr1.length; i++) {
      System.out.print(arr1[i] + "\t");
    }

    //printing a line
    System.out.println();
    System.out.println("Array elements of arr2: ");
    for (int i = 0; i < arr2.length; i++) {
      System.out.print(arr2[i] + "\t");
    }

    //printing a line
    System.out.println();
    System.out.println("Array elements of arr3: ");
    for (int i = 0; i < arr3.length; i++) {
      System.out.print(arr3[i] + "\t");
    }

    //printing a line
    System.out.println();

  }
}

Output

The output of the above example is:

Array elements of arr1: 
10      20      30      40      50
Array elements of arr2: 
100     200     300     400     500
Array elements of arr3: 
11      22      33      44      55

Another Example: Create an integer array, assign, and print the values

// Java program to create an integer array, 
// assign, and print the values

class Main {
  public static void main(String[] args) {
    // declare an integer array
    int[] intArr;

    // allocate memory for 5 integers
    intArr = new int[5];

    // initialize the first element
    intArr[0] = 10;

    // initialize the second element
    intArr[1] = 20;

    // And, so on...
    intArr[2] = 30;
    intArr[3] = 40;
    intArr[4] = 50;

    // accessing all  elements
    for (int i = 0; i < intArr.length; i++)
      System.out.println("Element at index " + i +
        " : " + intArr[i]);
  }
}

Output

The output of the above example is:

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.