Arrays in Java(Overview)

Introduction:

In Java, an array is a data structure that allows you to store a collection of items, all of the same type. The items are stored in a specific order and can be accessed using an index, which is a number that corresponds to the position of the item in the array.

For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names.

String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed.

Types of Array in java

There are two types of arrays.

  • Single Dimensional Array

  • Multidimensional Array

Syntax of an Array in Java**

  1. dataType[] arr; (or)

  2. dataType []arr; (or)

  3. dataType arr[];

Instantiation of an Array in Java.

  1. When an array is declared, only a reference of an array is created. To create or give memory to the 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];

    Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To 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

Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.

Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, a collection framework is used in Java which grows automatically.