Initialize empty array in java

Initialize empty array in java

💡 Outline
You can use below code to initialize empty array in java.

Introduction

In this post, we take a look on How to Initialize empty array in Java. We will look at different ways to Initialize arrays in Java with dummy values or with prompted user inputs. Arrays in Java follow a different declaration paradigm than other programming languages like C, C++, Python, etc.

In Java, array is by default regarded as an object and they are allocated memory dynamically. Moreover, in java at the time of creation an array is initialized with a default value. For Example: If the array is of type int(integer) all the elements will have the default value 0.

Hence, we will outline different methods to initialize an empty array with examples, to make it easy for a beginner in Java to use appropriate example under apt cases.

How do you initialize an empty array in java?

Considering all cases a user must face, these are the different methods to initialize an array:

  • Using new Keyword with predefined values and size.
  • Using Anonymous Array objects.
  • Using java.util.Scanner Class for user input with predefined size.
  • Using java.io.BufferedReader for user input with unknown size.
  • Using fill() method of java.util.Arrays Class.

Let us look at these methods in detail.

Using new Keyword with predefined Values and Size

An empty array can be initialized with values at the time of declaration only. The new keyword allocates memory to the array dynamically in the heap. The Syntax of declaring an array is:

However, We can provide the values inside the curly braces while declaring the array. In such case, the size is not provided inside the square brackets.

Code Example – new keyword to initialize an empty array in java

Let us understand this with a code snippet.

Output:

The Arrays.toString() method of Arrays class, prints the String representation of the array, it is present in java.util package. This approach is recommended when the values and the number of elements i.e. the size are known to us.

An Alternative Approach that Java supports to initialize an array is defining the array directly with predefined values without using the new keyword. Let us look at the code example:

This is a valid array initialization in Java that follows similar style to that of C/C++ and the above code will produce the same output a shown above.

Unlike the above approach we can also declare an array with predefined size . In such a case, the array has to be initialized with values explicitly using either a loop or user input. We define the size within the square brackets [].

Code Example – new Keyword to initialize array with predefined size

Output:

Using Anonymous Array Objects to initialize empty array

This is an interesting way to initialize array within memory without actually creating the object. Suppose, we have an array in a class and we want to initialize it without creating the array object.

To achieve this, we can pass an Anonymous Array Object i.e. an Anonymous Object to a method of the class which contains the actual array. In this way we can initialize the array without creating a named object.

Code Example – Initializing array using Anonymous Objects in java

Let us look at the code snippet of how we can actually do this. We will create a method or constructor to initialize the array of the class.

Output:

Using java.util.Scanner Class for user input with predefined size. 

Now, if the array needs to be initialized with values prompted by the user as a input. For this, we can use the Scanner Class present in java.util package that handles user input.

In such case, the size of the input must be known before hand as we have to create the array object with given size. After this, we can loop through the size of array and take input to initialize the array.

Code Example- Initializing Arrays using Scanner Class

Let us look at the code snippet for this approach.

Output:

Using java.io.BufferedReader to initialize array for user input with unknown size

There is another way to initialize array when user input is our concern. Suppose we need to initialize an array with values of unknown size or when the length of the input is unknown. In such case, we can use the BufferedReader Class of java.io package. It reads inputs in streams independent of the length.

The input that can be read by BufferedReader object can be of type String only. Hence, we can only use String type array to take inputs. We can later convert or parse the input to the datatype of our choice.

Code Example – Initialize array using BufferedReader Class

Let us look at the code snippet for this approach.

Output:

Initialize Empty Array Using BufferedReader

Using fill() method of java.util.Arrays Class to initialize empty array

This is an interesting way to initialize or fill an array with some given values. The drawback of this approach is that we can fill the array only with one given value.

However, we can also fill a part of the array by providing array indices to the fill() method.

Code Example- Initialize Array using Arrays.fill() method

Let us look at the code for this method.

Output:

That’s all about how to initialize empty array in java. We had a look on different ways to initialize empty arrays with detailed explanation. Feel free to leave your suggestions/doubts in the comment section below.

Was this post helpful?

Related Posts

  • 17 May

    How to Initialize an Array with 0 in Java

    Table of ContentsArraysInitializing Newly Created ArrayUsing Default Initialization of Arrays in JavaUsing Initialization After DeclarationUsing Simultaneous Initializing and Declaration of ArrayUsing Reflection in JavaInitializing Existing ArrayUsing the Arrays.fill() Function of JavaUsing the for LoopUsing Reassignment From Another ArrayUsing Collections.nCopies() Function of JavaInitializing User-Defined Object ArrayConclusionWas this post helpful? This article discusses the arrays and different […]

  • Set an array to another array in java
    23 April

    Set an Array Equal to Another Array in Java

    Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]

  • Check if array is empty in Java
    04 March

    Check if Array Is Empty in Java

    Table of ContentsCheck if the Array Is Empty in JavaThe Array Variable Has the Null ReferenceThe Array Does Not Contain Any ElementThe Array Has Only Null ElementsUsing the Java Library to Check if the Array Is Empty in JavaUsing Apache Commons Library to Check if the Array Is Empty in JavaConclusionWas this post helpful? In […]

  • Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers
    07 April

    Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers

    In this article, we look at a problem : Given an Array of Positive Integers, Find the [Maximum Difference](https://java2blog.com/maximum-difference-between-two-elements-in-array/ "Maximum Difference") between Two Adjacent Numbers. For each pair of elements we need to compute their difference and find the Maximum value of all the differences in array. Let us look at an example, Consider this […]

  • 11 November

    How to print array in java

    Learn about how to print array in java in multiple ways.

  • 09 October

    Initialize 2D array in Java

    Table of ContentsInitialize 2D array Using for loopInitialize 2D array using an initializerInitialize 2D array of variable columns lengthInitialize 2D array with heterogeneous dataInitialize 2D array using initialilzer with columnsInitialize 2D array using Reflection APIInitialize 2D array using the toCharArray()Was this post helpful? In this article, we will learn to initialize 2D array in Java. […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.