Java

Creating Arrays in Java

Programmingempire

In this article, I will explain Creating Arrays in Java. To begin with, let us first understand what an array is. Basically, an array represents a collection of elements. So, an array can contain multiple values of the same data type. Additionally, all elements in an array occupy the contiguous locations in memory. Further, all the elements of an array can be accessed in a program by using the name of the array. However, to distinguish different elements, a subscript or index is used. Furthermore, the index starts with 0 in Java. The following figure describes an array of integers.

Array Representation
Array Representation

Important Points Regarding Arrays in Java

  • In Java, arrays are dynamically created. Therefore, just declaring an array doesn’t allocate memory to it. So, we need to use the new keyword to allocate memory t an array.
  • Since arrays are directly inherited from the class Object, they are also considered as objects in Java.
  • Each array has a length property.
  • Also, each array has an associated class object.

How to Create Arrays in Java?

While creating an array in Java, the following syntax is used. At first, we need to specify the data type followed by the square brackets. After that, we specify the array name. In order to allocate memory, either we need to use new keyword, or initialize it with comma-separated values enclosed in curly brackets. The following code demonstrates creating an arrays in Java using different ways.

//Declaration
data-type[] array-name;

data-type array-name;

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

array-name={value 1, valure 2, value3,.....value n}

Examples of Creating Arrays in Java

The following code shows some examples of creating arrays. As can be seen, the length property returns the total number of elements in the array.

package ArrayExamples1;
public class A {
	public static void main(String[] args) {
		int[] arr1=new int[5];
		System.out.println("Length of first array: "+arr1.length);

		int arr2[];
		arr2=new int[4];
		System.out.println("Length of second array: "+arr2.length);

		int[] arr3;
		arr3=new int[10];
		System.out.println("Length of third array: "+arr3.length);

		int[] arr4= {12, 10, 55, 89, 78, 55};
		System.out.println("Length of fourth array: "+arr4.length);
	}
}

Output

Example of Creating Arrays in Java
Example of Creating Arrays in Java

Although, arrays have many advantages, there is one drawback. Even if the requirement is less, the memory equivalent to the size of array remains allocated. Hence, in case of arrays containing lesser elements than their size, lots of wastage of memory space happens.


programmingempire

You may also like...