Java Array – Declare, Create & Initialize An Array In Java

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 7, 2024

This In-depth Tutorial Explains Various Ways to Declare, Create and Initialize a New Array With Values in Java with the Help of Simple Code Examples:

In our previous tutorial, we discussed the basics of arrays in Java along with the different concepts associated with arrays which we will learn in detail in this tutorial series.

The first and foremost step with arrays is to create them. You need to be aware of what type of elements and how many elements you are going to store in arrays. Once you declare an array, you might want to initialize them by providing some initial values and there are various methods to do this.

Declare Create Java Array

Thus in this tutorial, we will focus on creating and initializing arrays before moving on to other concepts.

How To Declare An Array In Java?

In Java, a one-dimensional array is declared in one of the following ways:

data_type[] array_name; {or}
data_type array_name[]; {or}
data_type []array_name;

Here the ‘data_type’ specifies the type of data the array will hold. The ‘data_type’ can be a primitive data type or any derived type.

For Example, an array myarray of type integer is declared as follows:

int[] myarray;
OR
int []myarray;
OR
int myarray[];

This means that the array myarray will hold the elements of data type int.

Note that as the arrays in Java are dynamically allocated, we do not specify any dimension or size of the array with the declaration. The above declaration tells the compiler that there is an array variable ‘myarray’ of type int which will be storing the integer type values in it.

The compiler does not know the size or actual values stored in an array. It will only know that after we initialize the array.

Instantiate And Initialize A Java Array

We have already declared an array in the previous section. But this is just a reference. In order to use the above-declared array variable, you need to instantiate it and then provide values for it. The array is instantiated using ‘new’.

The general syntax of instantiating is as follows:

array_name = new data_type [size];

In the above statement, array_name is the name of the array being instantiated.

data_type=> type of elements the array is going to store

size=> the number of elements that will be stored in array

Hence when you use new with the array, you are actually allocating the array with the data type and the number of elements.

So the above-declared array myarray can be instantiated as follows:

myarray = new int[10]

Thus creating an array in Java involves two steps as shown below:

int[] myarray;			//declaration
myarray = new int[10]; 	//instantiation

Once the array is created, you can initialize it with values as follows:

myarray[0] =  1;
myarray[1] = 3; ….and so on until all elements are initialized.

The expression in the square brackets above is called the index of the array. The index of the array is used to access the actual value of the elements i.e. the above array myarray of 10 int elements will have indices numbered from 0 to 9. You can access the element of the array at a particular position by specifying the index as above.

Note that the array index always starts from 0. Alternatively, you can also do the initialization using a loop which we will see later on.

You can also use array literal and initialize array during declaration itself as shown below:

int[] myarray = {1,3,5,7};

In the above statement, the length of the array is determined by the number of elements. Also, as you can see there is no need to use ‘new’. More importantly, the declaration, instantiation and the initialization of the array is done in a single statement.

Given below is a simple programming example of declaring and initializing the array.

public class Main
{
public static void main(String[] args)
        {
	    int[] myarray;			//declaration
	    myarray = new int[5];	//instantiation
	    myarray[0] = 10;		//initialization
	    System.out.println("myarray[0] = " + myarray[0]);  //accessing and printing array elements
	    System.out.println("myarray[1] = " + myarray[1]);
	    int [] oddArray = {1,3,5,7};	//initialization with array literal
            System.out.println("oddArray[0] = " + oddArray[0]);
	    System.out.println("oddArray[1] = " + oddArray[1]);
	    System.out.println("oddArray[2] = " + oddArray[2]);
	    System.out.println("oddArray[3] = " + oddArray[3]);
        }
}

Output:

Declaring and initializing the array_output

This program demonstrated an array declaration and its instantiation as well as initialization. Note that as we have only initialized the oth value of myarray, the other value myarray[1] that is printed has a default value i.e. 0.

The second array demonstrates the array literal variable. Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element.

We will demonstrate these default values using the following program.

class Main 
{ 
  public static void main(String[] args)     { 
   System.out.println("=======Default Values======");
   System.out.print("String Array:"); 
   String[] array_str = new String[5]; 		//declaration and instantiation
   for (String str : array_str) 			//assumes default values
         System.out.print(str + " ");             
   System.out.println("\n");

   System.out.print("Integer array:"); 
   //array only instantiated not initialized
   int[] array_num = new int[5]; 
   for (intnum : array_num) 
          System.out.print(num + " ");   
   System.out.println("\n");

   System.out.print("Double array:"); 
   //array only instantiated not initialized
   doublearray_double[] = new double[5]; 
   for (double dnum : array_double) 
       System.out.print(dnum + " ");   

   System.out.println("\n");
   System.out.print("Boolean array:"); 
   //array only instantiated not initialized
   booleanarray_bool[] = new boolean[5]; 
   for (booleanbval : array_bool) 
         System.out.print(bval + " "); 
   System.out.println("\n");
    } 
}

Output:

default values_output

In the above program, we have just declared and instantiated them. We have not initialized them to any values. Thus, when we display the contents of these arrays, depending on the data type of the array, the elements will have different default values.

As seen above, string array has default as ‘null’, integer values are 0 and double values default to 0.0. Boolean values have their default values set to false.

Initializing And Accessing Array Elements

#1) Using For Loop

The program written above uses an array literal for initializing and the other array elements are initialized separately. You can also use for loop to initialize the array elements.

We have converted the above array using array literal to initialize it using for loop in the below program.

public class Main
{
    public static void main(String[] args)
    {
	int[] oddArray;			//declaration
	oddArray = new int[5];		//instantiation
	for(int i=0;i<5;i++){		
	     oddArray[i] = i+1;		//initialization using for loop
	}
	System.out.println("oddArray[0] = " + oddArray[0]);
	System.out.println("oddArray[1] = " + oddArray[1]);
	System.out.println("oddArray[2] = " + oddArray[2]);
	System.out.println("oddArray[3] = " + oddArray[3]);
	System.out.println("oddArray[4] = " + oddArray[4]);
     }
}

Output:

Array literal to initialize it using for_loop

Here, as you can see we have initialized the array using for loop. Each element ‘i’ of the array is initialized with value = i+1. Apart from using the above method to initialize arrays, you can also make use of some of the methods of ‘Arrays’ class of ‘java.util’ package to provide initial values for the array.

We will discuss some of these methods below.

#2) Using Arrays.fill()

The fill() method of the ‘Arrays’ class can be used to initialize the array. When you initialize an array using this method, the array is filled with the same values at all indices.

Given below is the programming example.

import java.util.*;
public class Main
{
      public static void main(String[] args)
      {
	  int[] oddArray;
	  oddArray = new int[5];
      //fill the array with value 30	
     Arrays.fill(oddArray, 30);
     System.out.println("Array Elements initialised with Arrays.fill:");
     for(int i=0;i<5;i++)
	  System.out.println("oddArray[" + i +"] = " + oddArray[i]);
      }
}

Output:

Fill method of Arrays_class

In the above program, we have provided 30 as the value to be filled for the array. The output shows that all the elements in the array have value as 30.

#3) Using Arrays.copyOf()

Using the method ‘copyOf()’, we use a source array and then copy its values into a new array. You can specify how many values are to be copied and then the remaining elements of the array will have default values.

Check the following program.

import java.util.*;
public class Main
{
      public static void main(String[] args)
      {
	  int evenArray[] = { 2,4,6,8,10 };
	  //copy contents of evenArray to copyof_Array
	  int[] copyof_Array = Arrays.copyOf(evenArray,5);
          System.out.println("Array Elements initialised with Arrays.copyOf:");
          //print the array elements
	  for(int i=0;i<5;i++)
	       System.out.println("copyof_Array[" + i +"] = " + copyof_Array[i]);
        }
}

Output:

Using_Arrays.copyOf

In this program, we use a source array named ‘evenArray’. Using the copyOf method we have copied all the elements of evenArray into the new array. In the output, we display the contents of the new array which are the same as evenArray.

Apart from the above two methods we just discussed that there are more methods like the setAll () method of Arrays class and clone() method of ArrayUtils that can be used to initialize arrays. We will take up these methods later in this tutorial series in the respective topics.

Frequently Asked Questions

Q #1) Can we declare an Array without size?

Answer: Yes. We can declare an array without size but before using it needs to be initialized.

Q #2) Is Array size fixed in Java?

Answer: Yes. Arrays are static in Java and you declare an array with a specified size. Once this size is specified, you cannot change it again.

Q #3) Is it always necessary to use new while initializing arrays?

Answer: No. Arrays can be initialized using new or by assigning comma-separated values enclosed in curly braces.

So when we initialize an array using Array literal as shown below. You do not need to use new ones.

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

The number of elements provided will determine the size of the array.

Q #4) Is Java Array serializable?

Answer: Yes. Internally the Array in Java implements the serializable interface.

Q #5) Is an Array Primitive data type?

Answer: No. In fact, an array is not a data type at all. An array is a container object that holds the elements of specific data types in contiguous memory locations.

Conclusion

This sums up the creation and initialization of arrays in Java. Once the arrays are created and initialized to some values, we need to print them. For printing the array elements, we need to traverse the entire array and print elements.

We will look into some of the methods of printing array elements in our next tutorial.

Was this helpful?

Thanks for your feedback!

Leave a Comment