Java Array Initialization Techniques

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn the different ways to initialize an array in Java. You will also learn how to use the Scanner class to take user input, how to use nested loops to initialize a 2D array, how to initialize an array at the time of declaration, and how to use different methods like Arrays.fill(), Arrays.setAll(), and ArrayUtils.clone().


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ProgrammingTechniquesGroup -.-> java/lambda("`Lambda`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/recursion -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/scope -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/lambda -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/oop -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/user_input -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/identifier -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/arrays -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/data_types -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/for_loop -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/operators -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/output -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/strings -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/variables -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/arrays_methods -.-> lab-117460{{"`Java Array Initialization Techniques`"}} java/system_methods -.-> lab-117460{{"`Java Array Initialization Techniques`"}} end

Declaring and Initializing Arrays

Before initializing an array, we must know how to declare an array. Declaring means defining the variable name and the data type of the elements that will be stored in the array. The general syntax of declaring an array is shown by the code below.

datatype[] variableName;

Initializing an array is setting an initial value to the array elements. We can initialize an array using the different ways explained below.

Initializing All Array Elements to Zero

To initialize an array with all elements set to 0, we only need to declare the array and initialize it to the required size using the new keyword. Java initializes all array elements to their default values (0 for integer, null for string, false for Boolean, etc.) by default.

int[] intArray = new int[5];

Initializing Array Elements One at a Time

To initialize each element of an array one-by-one, we can use a for loop to initialize the array indices.

int[] intArray = new int[5];
for(int i = 0; i < intArray.length; i++) {
    intArray[i] = i + 1;
}

Initializing an Array at the time of Declaration

We can declare an array and initialize it at the same time with just a single line of code.

int[] intArray = {1, 2, 3, 4, 5};

Using the Scanner Class to Take User Input

To initialize an array with user input, we can use the Scanner class to read input from the user.

Scanner input = new Scanner(System.in);
System.out.print("Enter array length: ");
int length = input.nextInt();

int[] intArray = new int[length];
for(int i = 0; i < length; i++) {
    System.out.print("Enter element " + (i + 1) + ": ");
    intArray[i] = input.nextInt();
}
input.close();

Initializing a 2D Array

We can use nested loops to initialize a 2D array.

int[][] intArray = new int[3][3];
for(int i = 0; i < intArray.length; i++) {
    for(int j = 0; j < intArray[i].length; j++) {
        intArray[i][j] = i + j;
    }
}

Using Arrays.fill() Method

We can use the Arrays.fill() method to initialize an array with a specific value.

int[] intArray = new int[5];
Arrays.fill(intArray, 5);

Using Arrays.setAll() Method

We can use the Arrays.setAll() method to Initialize the array with the help of a Generator Function.

int[] intArray = new int[5];
Arrays.setAll(intArray, (index) -> index * index);

Using ArrayUtils.clone() Method

We can use the ArrayUtils.clone() method to create a copy of an existing array.

int[] intArray = new int[] {1, 2, 3, 4, 5};
int[] copyArray = ArrayUtils.clone(intArray);

Using Arrays.copyOf() Method

We can use the Arrays.copyOf() method to create a copy of an existing array.

int[] intArray = new int[] {1, 2, 3, 4, 5};
int[] copyArray = Arrays.copyOf(intArray, 8);

Summary

In this lab, you learned different ways of initializing an array in Java using for loops, declaring and initializing at the same time, using the Scanner class for user input, initialization at declaration, using the Arrays.fill() and Arrays.setAll() method, and copying an array using the ArrayUtils.clone() and Arrays.copyOf() methods. Now you are able to initialize an array in several ways depending on your program needs.

Other Java Tutorials you may like