Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Initialize empty array in java

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

//declaring array of size 3
int array[] = new int[3];

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:

data-type[] array-name = new data-type[size];
//or
data-type array-name[] = new data-type[size];

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.

import java.util.*;
public class Java2Blog {
    public static void main(String args[]) {

        //declaring array and initializing it with values passed in curly braces.
        int array[] =new int[]{1,2,3,4,5};
        // using toString method of Arrays class to print Array.
        System.out.println(Arrays.toString(array));
    }
}

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:

import java.util.*;
public class Java2Blog {
    public static void main(String args[]) {

        //declaring array without new keyword
        int array[] = {1,2,3,4,5};
        // using toString method of Arrays class to print Array.
        System.out.println(Arrays.toString(array));
    }
}

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

import java.util.*;
public class Java2Blog {
    public static void main(String args[]) {

        //declaring array of size 5
        int array[] = new int[5];

        //using for loop to fill array with values. 
        for(int i=0;i
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.

import java.util.*;
class Sample
{
    int array[];
    Sample(int arr[])
    {
        // we assign the arr value to array of class Sample
        array = arr;
    }
}

public class Java2Blog {
    public static void main(String args[]){
      //                     Creating anonymous array object and passing it as a parameter to Constructor.    
      Sample obj = new Sample(new int[]{3,2,1});
      System.out.println(Arrays.toString(obj.array));
    }
}

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.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {
    public static void main(String args[]) {

        // String to be scanned to find the pattern.
        String line = "This order was placed for QT3000! OK?";
        String pattern = "(.*)(\\d+)(.*)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        if (m.find()) {
            System.out.println("Found value: " + m.group(0));
            System.out.println("Found value: " + m.group(1));
            System.out.println("Found value: " + m.group(2));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

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.

import java.io.*;
import java.util.*;
public class Java2Blog {
    public static void main(String args[]) throws IOException {

        //declaring BufferedReader object to take input.
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter Array Input String: ");

        // taking input using readLine method.
        // then splitting the string with split() method accordingly based on space
        // then we fill the array.
        String array[] = br.readLine().trim().split(" ");

        // using toString method of Arrays class to print Array.
        System.out.println("The Array is: " + Arrays.toString(array));
    }
}

Output:

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.

import java.util.*;
public class Java2Blog {
    public static void main(String args[]) {

        int a[] = new int[5];
        // Calling fill() method and passing 10 as value to fill the total array
        Arrays.fill(a, 10);
        System.out.println("Array after complete filling: " + Arrays.toString(a));

        // Calling fill() to fill part of array
        // It will start filling from first index to last index - 1 position.
        // so it fills array a from index 2 to 3 with value 30.
        Arrays.fill(a, 2, 4, 30);
        System.out.println("Array after being partly filled: " + Arrays.toString(a));

    }
}

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.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

Initialize empty array in java

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×