Array initialization in Java

An array is an indexed collection of fixed no of homogeneous data elements.


An array represents a group of elements of the same data type.

.
The main advantage of an array is we can represent a large number of elements by using a single variable. So that readability of the code will be improved.

In this article we will see, how to use array in java.we will learn how to declare, initialize, and access array elements with examples.

Here are some points point about Java arrays.

An array contains primitives (int, char, etc) as well as to object (or non-primitive) references of a class depending on the definition of the array. For primitives data types, the actual values are stored in contiguous memory locations.

arrays are objects in Java, we can find their length using member length.

The direct superclass of an array type is Object.

Java array can be used as a static field, a local variable, or a method parameter.

A Java array variable can also be declared like other variables with [] after the data type.

Every array of ant data types implements the interfaces Cloneable and java.io.Serializable.

Array initialization in Java How to declare an array?

type[] array;

type it can be primitive data types like int, char, double, byte, String, Object, etc.

int[] numbers;

how many elements can array this hold?

array = new int[10];

Once the length of the array is defined, it cannot be changed in the program, but reference can be changed.

int[] numbers; numbers = new int[8]; int[] numbers0 = new int[10]; numbers = numbers0; Object[] o=new Object[10000]; o[0]=new Student(); o[1]=new Customer(); int intArray[]; or int[] intArray;

Examples:
byte bytes[]; short shorts[]; long longArray[]; float floatArray[]; boolean bools[]; double doubles[]; char chars[]; // an array of references to objects of // the class MyClass (a class created by // user) MyClass myClassArray[]; Object[] ao, // array of Object Collection[] ca; // array of Collection

 Instantiating an Array in Java

When an array is declared, only a reference of an array is created. To actually create or give memory to an array,
you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows:

var-name = new type [size];

use new to allocate an array, you must specify the type and number of elements to allocate.

Example:
int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array

The elements in the array allocated by new will automatically be initialized to zero (for numeric types),
false (for boolean), or null (for reference types). Refer Default array values in Java.

Obtaining an array is a two-step process. First, you must declare a variable of the desired array type.
Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

Array Literal

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

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

Declaring array literal The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of an array can be accessed using Java for Loop.
package com.javacodestuffs.core.arrays; public class ArrayExample { public static void main (String[] args) { // declares an Array of integers. int[] array; array = new int[3]; array[0] = 121; array[1] = 555; array[2] = 128; for (int i = 0; i < array.length; i++) System.out.println("Element at " + i + " location is : "+ array[i]); } } output: $javac com/javacodestuffs/cores/arrays/ArrayExample.java $java -Xmx128M -Xms16M com/javacodestuffs/core/arrays/ArrayExample Element at 0 location is : 121 Element at 1 location is : 555 Element at 2 location is : 128

Arrays of Objects

An array of objects can be created like an array of primitive data types.

Employee[] empArray = new Employee[4]; //student is a user-defined class

The empArray contains four memory spaces each of the size of Employee class in which the address of four Employee objects can be stored.

package com.javacodestuffs.core.arrays; class Employee { public int id; public String name; Employee(int id, String name) { this.id = id; this.name = name; } } public class ArrayOfObjects { public static void main(String[] args) { // declares an Array of Objects. Employee[] empArray; empArray = new Employee[4]; empArray[0] = new Employee(1, "Anna"); empArray[1] = new Employee(2, "Bala"); empArray[2] = new Employee(3, "Rashmika"); empArray[3] = new Employee(4, "Sulesh"); for (int i = 0; i < empArray.length; i++) System.out.println("Element at " + i + " location: " + empArray[i].id + " " + empArray[i].name); } } output: $javac com/javacodestuffs/cores/arrays/ArrayOfObjects.java $java -Xmx128M -Xms16M com/javacodestuffs/core/arrays/ArrayOfObjects Element at 0 location: 1 Anna Element at 1 location: 2 Bala Element at 2 location: 3 Rashmika Element at 3 location: 4 Sulesh

if we try to access an element outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22 at com.javacodestuffs.cores.arrays.ArrayOfObjects.main(ArrayOfObjects.java:32)

package com.javacodestuffs.core.arrays; public class ArrayExample1 { public static void main (String[] args) { int[] numbers = new int[5]; numbers[0] = 21; numbers[1] = 11; numbers[1] = 51; for (int i = 0; i <= numbers.length; i++) System.out.println(numbers[i]); } } output: 21 51 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.javacodestuffs.core.arrays.ArrayExample1.main(ArrayExample1.java:12)

Computes sum and average of given integers using the array

package com.javacodestuffs.cores.arrays; public class SumAvgUsingArray { public static void main(String[] args) { int[] numbers = { 12, 11, 56, 45, 124, 22, 56, 91, 73, 99, 41, 19 }; int sum = 0; Double avg; for (int number: numbers) { sum += number; } avg = ((double) sum / (double) numbers.length); System.out.println("Sum of numbers is : " + sum); System.out.println("Average of numbers is :" + avg); } } output: Sum of numbers is : 649 Average of numbers is :54.083333333333336

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of another array.
These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix int[][][] intArray = new int[10][20][10]; //a 3D array

package com.javacodestuffs.core.arrays; public class multiDimensionalArray { public static void main(String args[]) { // declaring and initialize 2D array int arr[][] = { { 1, 2, 3 }, { 9, 8, 7 }, { 6, 5, 4 } }; System.out.println("MultiDimensional Array is : "); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } } output: MultiDimensional Array is : 1 2 3 9 8 7 6 5 4

Cloning of arrays

We can clone the arrays as arrays are direct child class of Objects class, but the internal cloning mechanism is different for normal one-dimensional array and multidimensional array.

1). To clone a single-dimensional array, such as Object[], a DEEP copy is performed with the new array containing copies of the original array's elements.

2). To multidimensional array (like Object[][]) is a SHALLOW copy is created, which creates only a single new array with each element array a reference to an original element array but subarrays are shared.

Returning Arrays from Methods

We can return the array to the method.ie When we call a method from another code location.

package com.javacodestuffs.core.arrays; public class ReturnArray { public static void main(String args[]) { int arr[] = getArrayOfIntegers(); System.out.print("Array returned from Method is : "); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); } public static int[] getArrayOfIntegers() { // returning array to method return new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; } } output: Array returned from Method is : 9 8 7 6 5 4 3 2 1

Members of Array

We know that the direct superclass of arrays is class Object. arrays are objects of a class. Members of an array type are :

The public final field length(positive or zero), which contains the number of components of the array.

All the members inherited from class Object, but the only method of Object that is not inherited is its clone method.

The public method clone(), which overrides the clone method in class Object.

For-each Loop for Java Array

We can print the Java array using a for-each loop. the elements printed one by one.
package com.javacodestuffs.core.arrays; public class ForEachOnArray { public static void main(String args[]) { int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; System.out.println("Elements of array are : "); for (int i: arr) { System.out.println(i); } } } output: Elements of array are : 9 8 7 6 5 4 3 2 1

Anonymous Array in Java

Java supports the feature of an anonymous array. We don't need to declare the array while passing an array to the method as arguments.

package com.javacodestuffs.core.arrays; public class AnonymousArray { public static void main(String args[]) { System.out.println("The Anonymous Array elements are : "); printIt(new int[] { 71, 51, 31, 11, 21 }); //passing anonymous array to method } static void printIt(int arr[]) { for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); } } output: The Anonymous Array elements are : 71 51 31 11 21

How to initialize the array in java with 0?
How to initialize the array in constructor java?
How to initialize a generic array in java?
How to initialize 3d array in java?
How to initialize byte array in java?
How to initialize an array in java?
How to initialize string array in java?
Which will legally declare construct and initialize an array?

Limitations of Object[] array

1).  Arrays are fixed in size that is once we created an array there is no chance of increasing
(or) decreasing the size based on our requirement hence to use arrays concept compulsory we should know the size in advance which may not possible always.

2).  Arrays can hold only homogeneous data elements.

3).  Arrays concept is not implemented based on some data structure hence ready-made methods support we can't expert. For every requirement, we have to write the code explicitly.

To overcome the above limitations we should go for collections concept.

In this article, we have seen the  Array initialization in Java with examples. All source code in the article can be found in the GitHub repository.