Arrays

Arrays

What is an Array?

An array is a collection of similar types of Elements. It is a data structure where we store similar elements. **Elements of an Array are stored in continuous memory allocation. Arrays are index-based, the first element of the array is stored at the 0th index so on. When we declare an array int[] roll_nums = new int[10]; here array is allocated a size of 10 but the index starts from 0 and ends at9. **

          dataType[] arrayName; //declaring array
          arrayName  = new dataType[arraySize]; // allocating memory 

        datatype[] variable_name = new datatype[size];

Example:

        int[] roll_nums = new int[5]; // It creates an array of size 5 which can store 5 numbers;

Array's in Java

An array is used to store a collection of data, but it is also more useful to think of an array as a collection of variables of the same type. The class java.util.Arrays have some methods. These methods can get applied to the array to get the index of the array, length of arrays.

In Java, arrays follow dynamic memory allocation, unlike C/C++ which follows continuous memory allocation.

An Array can be of primitive data type and non-primitive (obj) when an array is declared as primitive it stores in contiguous memory. In the case of non-primitives(objects) stored in a heap segment (Dynamic).

We can also create single dimensional or multidimensional arrays in Java.

Advantages

**Elements can be accessed randomly by using the index number. ** Arrays in java can be passed in Methods Arrays are fast to perform operations like sorting, search and accessing elements.

Disadvantages

** The array has a fixed size **

** We cannot increase or decrease the size of the array at runtime **

** We can store similar data type items only. **

Applications

  1. Array stores data elements of the same data type.

  2. Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoids the confusion of using multiple variables.

  3. Arrays can be used for sorting data elements. Different sorting techniques like the Bubble sort, Insertion sort, Selection sort etc use arrays to store and sort elements easily.

  4. Arrays can be used for performing matrix operations. Many databases, small and large, consist of one-dimensional and two-dimensional arrays whose elements are records.

  5. Arrays can be used for CPU scheduling.

  6. Lastly, arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash tables etc.