How to Initialize an Array in Java – [With Examples]

In Java, an array is a collection of like-typed variables with a common name, Arrays in Java are not the same as those in C/C++. The following are some key points to remember regarding Java arrays.

All arrays in Java are allocate dynamically. Because arrays are objects in Java, we may use the object attribute length to determine their length. This differs from C/C++, where we use size to find the length.

  • With [] following the data type, a Java array variable can be declare just like any other variable.
  • The array’s variables are sort, and each has an index starting at 0.
  • A static field, a local variable, or a method parameter can all be utilize with a Java array.
  • An array’s size must be given using an int or short integer rather than a long number.
  • An object is the array type’s direct superclass.
  • Every array type implements the Cloneable and java.io interfaces.

Depending on the array’s definition, it can contain primitives (int, char, etc.) as well as to object (or non-primitive) references to a class. The actual values of primitive data types are store in contiguous memory regions. The real objects are kept in a heap section in the case of class objects.

Creating, Initializing, and Accessing an Array in Java

One-Dimensional Arrays – A one-dimensional array declaration takes the following general form:

type variableName [];
OR
type[]variableName;

The type and the name are the two parts of an array declaration. type specifies the array’s element type. The data type of each element in the array is determine by the element type. We can make an array of various primitive data types like char, float, double, and so on, as well as user-defined data types, similar to an array of integers (objects of a class). As a result, the array’s element type dictates the type of data it can carry.

Some Examples of the one-dimensional arrays are listed below:

  • boolean booleanArray[];
  • long longArray[];
  • float floatArray[];
  • double doubleArray[];
  • char charArray[];
  • MyClass myClassArray[];
  • Object[] abjArr,
  • Collection[] cal;

Despite the fact that the first declaration declares intArray to be an array variable, no actual array exists. It just informs the compiler that this variable (intArray) will contain an integer array. You must allocate a new and assign it to intArray to link intArray with an actual, physical array of integers.

Instantiating an Array in Java

Only a reference to an array is produce when an array is declare. You make an array like this to create or provide memory to the array: When it comes to one-dimensional arrays, the general form of new is as follows:

variableName = new type [size];

The type of data being allocate is specifies by type, size is determine by the number of items in the array, and var-name is the name of the array variable connect to the array. You must specify the type and number of elements to allocate when using new to allocate an array.

int newArray[];    
newArray = new int[20];  
OR 
int[] newArray = new int[20]; 

The items of the array allocated by new will be set to zero (for numeric types), false (for boolean types), or null by default (for reference types). Refer Java’s default array values

A two-step procedure is require to obtain an array. To begin, create a variable with the specified array type. Second, you must use new to allocate memory for the array and assign it to the array variable. As a result, all arrays in Java are dynamically allocate.

Array Literal

In a situation where the size of the array and variables of the array are already known, array literals can be used. 

int[] newArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; 

The produced array’s length is determine by the length of this array. In the most recent versions of Java, there is no need to write the new int[] portion.

Example: Accessing Java Array Elements using for Loop

class ArrayUsingLoop
{
    public static void main (String[] args)
    {        
      int[] newArray;
         
      newArray= new int[5];
         
      newArray[0] = 1;
      newArray[1] = 2;
      newArray[2] = 3;
      newArray[3] = 4;
      newArray[4] = 5;
         
      for (int i = 0; i < newArray.length; i++)
         System.out.println("Array Element at index " + i +
                                      " : "+ newArray[i]);         
    }
}

Output:

array in java img1

Arrays of Objects

The following code creates an array of objects in the same way that it creates an array of primitive type data items.

Police[] arr = new Police[21]; //student is a user-defined class

The policeArray has the addresses of all police officer’s objects in seven memory areas, each the size of a student class. The police objects must be create using the Police class’s function Object(), and their references must be assign to the array components as follows.

Police[] arr = new Police[30];

Example:

class Police
{
	public int id;
	public String name;
	Police(int id, String name)
	{
		this.id = id;
		this.name = name;
	}
}
class PoliceClass
{
	public static void main (String[] args)
	{
		
		Police[] array;
		array = new Police[4];
		array[0] = new Police(3242,"Peter");
		array[1] = new Police(4353,"Adil");
		array[2] = new Police(6433,"Preet");
		array[3] = new Police(3434,"Ranjeet");

		for (int i = 0; i < array.length; i++)
			System.out.println("Police array Element at " + i + " : " +
						array[i].id +" "+ array[i].name);

}
}

Output:

array in java img2

What happens if we try to access elements outside the array size?

When an array is access with an illegal index, the JVM throws an ArrayIndexOutOfBoundsException. An array’s index is either negative or larger than or equal to the array’s size.

Example:

class AccessArrayOutsie
{
    public static void main (String[] args)
    {
        int[] array = new int[3];
        array[0] = 3;
        array[1] = 5;
  	array[2] = 6;
 
        for (int i = 0; i <= array.length; i++)
            System.out.println(array[i]);
    }
}

Output:

array in java img3

Multidimensional Array in Java

Multidimensional arrays are collections of arrays, each of which contains references to other arrays. Jagged Arrays are another name for this type of array. One set of square brackets ([]) is append to each dimension to produce a multidimensional array. Examples:

int[][] array2D = new int[3][5]; //a 2D array or matrix
int[][][] array3D = new int[1][2][13]; //a 3D array

Example:

class multiDimensionalArray
{
    public static void main(String args[])
    {
  
        int multiDimensional[][] = { {1,2,3},{4,5,6},{7,8,9} };
 
        for (int i=0; i< 3 ; i++)
        {
            for (int j=0; j < 3 ; j++)
                System.out.print(multiDimensional[i][j] + " ");
 
            System.out.println();
        }
    }
}

Output:

img4

Passing Arrays to Methods

Arrays, like variables, can be passed to methods. For instance, in the program below, the array is passed to method sum, which calculates the sum of the array’s values.

Example:

class parsingArray
{   
    public static void main(String args[])
    {
        int array[] = {1, 2, 3, 4, 5};
        sum(array);
    }
    public static void sum(int[] array)
    {
        int sum = 0;   
        for (int i = 0; i < array.length; i++)
            sum+=array[i];
        System.out.println("sum of array values : " + sum);
    }
}

Output:

img5

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. What is Treemap in Java?
  2. What is a Thread in Java?
  3. How To Call a Method in Java – [With Examples]

Leave a Comment