Pages

Monday, October 12, 2020

How To Initialize An Array In Java In Different Ways

1. Overview

In this article, You'll learn how to initialize the array in java. Array creation can be done in different ways.

Typically, Arrays are a collection of the value of that of the same type. You can not store the different types of values inside the array.

This is the underlying structure that is widely used in the Collection API and problem solving interview questions.

All the values stored inside the array are called as elements and each element is stored at a unique index. Array index starts from ZERO.

How To Initialize An Array In Java In Different Ways


But, Collection api is preferred over arrays if you are doing insertions in middle or resizing the array.

2. How To Declare An Array?

Declaring array is pretty straight forward. Look at the below syntax.

DataType[] arrayName ;

All the below three segments are mandatory in the array declaration.

Data Type: Data type defines the type of objects or values are stored inside array such as int, boolean, char, float, etc.
[] : Square brackets indicates as an array.
arrayName: Variable name is to access the array values from memory.
package com.javaprogramto.arrays.initialize;

public class ArrayDeclaration {

    public static void main(String[] args) {
        
        // int array declaration
        int[] intArray;

        // boolean array declaration
        boolean[] statusArray;

        // float array declaration
        float[] salaryArray;
    }
}

3. Initializing An Array


In the above section, you understood how to declare an array. Now, let us understand some basic rules about the array initialization.

Declaring an array means that does not array is initialized. To store the values inside an array, You must have to initialize the array first.

Below is the syntax to initialize the array.
DataType[] arrayname = new DataType[size];
new keyword and size must be specified to create an array.

Array initialization can be done in different ways. Let us explore all the possible ways to create and store the values in an array.

4. Initializing An Array Without Assigning Values


Java allows initializing the values at all indexes at the time of its creation.

In the below example program, We are creating an array with its default values
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationDefaultValues {

    public static void main(String[] args) {

        // int array initialization
        int[] intArray = new int[9];

        System.out.println("Printing array values : ");
        for(int i = 0; i < intArray.length ; i++){
            System.out.println(intArray[i]);
        }

    }
}
Output:
Printing array values : 
0
0
0
0
0
0
0
0
0

Created and initialized an array with size 9 and did not assign any values in the program. When we run the for loop on intArray then it printed 0 for all indexes.

Note: Array length can be accessed through a special variable name called "length". This length is available on all array variables.

5. Initializing An Array After Declaration


If you observe in the above program, the Array is declared and initialized in a single line. But there is a way to declare the array first and next initialize an array with values.
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationAfterDeclaration {

    public static void main(String[] args) {

        // Example 1
        // int array declaration
        int[] intArray;

        // Array initialization
        intArray = new int[]{10, 20, 30, 40, 50};

        System.out.println("Printing array values : ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }

        // Example 2

        // Boolean array declaration
        boolean[] booleanArray ;

        // boolean array initialization
        booleanArray = new boolean[]{true, false, true};

        System.out.println("Printing boolean array : ");
        for(int index = 0;index < booleanArray.length; index++){
            System.out.println(booleanArray[index]);
        }
    }
}

Output:
Printing array values : 
10
20
30
40
50
Printing boolean array : 
true
false
true

In this example, Created two arrays, intArray stores int values, booleanArray stores boolean values.
These two arrays are first declared and in the next line initialized with its values.

Note: When an array is initialized with values in the next line than that array creation must use a "new" keyword. Otherwise, You will get the compile-time error saying "Array initialization is not allowed here"

6. Initializing An Array And Assigning Values Without Using new Keyword


Still, there is a way to initialize the array without using the new keyword. But, this is allowed only at the time of array declaration. If you try to do the same in the next line will give the compile-time error.

Let us see the examples.

int[] intArray = {2, 4, 6, 8, 20};

boolean[] booleanArray = {true, false, true};

double[] salaryArray = {15000, 35000, 50000};

Here, a new keyword is not used and size is calculated based on the values added to the array at declaration.

Full example program
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationWithoutNewKeyword {

    public static void main(String[] args) {

        // Example 1
        // int array declaration and intialization without new keyword
        int[] intArray = {2, 4, 6, 8, 20};

        System.out.println("Printing array values : ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }

        // Example 2

        // Boolean array declaration and intialization without new keyword
        boolean[] booleanArray = {true, false, true};

        System.out.println("Printing boolean array : ");
        for (int index = 0; index < booleanArray.length; index++) {
            System.out.println(booleanArray[index]);
        }

        // Example 3

        // Double array declaration and intialization without new keyword
        double[] salaryArray = {15000, 35000, 50000};

        System.out.println("Printing salary double array : ");
        for (int index = 0; index < salaryArray.length; index++) {
            System.out.println(salaryArray[index]);
        }
    }
}

7. Initializing the Wrapper Arrays and Employee Array


As of now, you've seen how to create and initialize an array for primitive types. But, the same can be applied to the Wrapper classes, String, and also for user-defined classes.

Observe the below examples and all are valid.
package com.javaprogramto.arrays.initialize;

import com.javaprogramto.models.Employee;

public class ArrayInitializationForNonPrimitives {

    public static void main(String[] args) {

        // Array initialization without the "new" keyword
        String[] stringArray = {"hello", "welcome"};

        // String Array initialization with "new" keyword
        String[] newStringArray = new String[]{"hello", "welcome"};

        Employee e1 = new Employee(100, "Jhon", 30);
        Employee e2 = new Employee(101, "Amal", 25);
        Employee e3 = new Employee(102, "Paul", 35);

        // Employee Array initialization without "new" keyword
        Employee[] empArrayWithoutNewKeyword = {e1, e2, e3};

// Employee Array initialization without "new" keyword Employee[] empArrayWithNewKeyword = new Employee[]{e1, e2, e3}; } }

8. Create and Initialize An Array With Size Zero(0)


Many developers who started learning java will get the common question is it possible to create an array with size 0?

The answer is yes it is possible and array has zero values in it and here are the few examples.
 		// Array initialization without the "new" keyword with size 0
        String[] stringArray = {};

        // String Array initialization with "new" keyword with size 0
        String[] newStringArray = new String[0];

        // Employee Array initialization without "new" keyword with size 0
        Employee[] empArrayWithoutNewKeyword = {};

        // Employee Array initialization with "new" keyword with size 0
        Employee[] empArrayWithNewKeyword = new Employee[0];
        

9. Conclusion


In this article, You've seen how to create and initialize an array in java in different ways.

Array related interesting articles others reading


All examples are shown are over GitHub.


No comments:

Post a Comment

Please do not add any spam links in the comments section.