Array in Java

Array in Java

Java Array Tutorials with examples

In this tutorial, you will learn about Arrays in Java, including how to declare an Array, initialize it, and access the Array, and how Array is stored in memory.

Before diving into the Arrays tutorial in Java, let's start with a simple scenario where you need to save five people's age in your code and later access the same for computation purposes.

You can declare five variables of int type to store the age.

int age1 = 10;
int age2 = 20;
.
.

Declaring five int variables seems more manageable, but what if we have to save 1000 people's age.

Can you imagine how messy it would be to create 1000 variables to store the age?

Here, Array comes to your rescue where you can store multiple elements of similar type in a single variable as below.

int [] age = new int[1000];

What is an Array?

Array in Java is the collection of similar data elements stored at a contiguous memory location. Depending on the declaration, an array can contain the primitive data type (int, char, etc.) or object. An array of primitives stores values of the primitives, and an array of objects stores only the references to the objects Array Data Structure in Java.png

How to declare an Array

To use an array in your code, you must declare the Array. In Java, here is how you can declare a one-dimensional array.

dataType [] variable_name;
dataType variable_name [];

dataType: dataType could be of primitive type (int, char, etc.) or objects (String, Integer, etc.) variable_name: it is an identifier for your Array

For example:

int [] age; or,
String [] name; or,
CustomClass [] customVariableName

This declaration defines the type of Array of int, String, or custom object, but no actual array exists until you instantiate the same; it simply tells the compiler that variable will hold the Array of provided data type.

How to instantiate the Array

When you declare an array, you create a reference only. To allocate the memory for your Array, you must instantiate the Array as follows:-

//declare an array
dataType [] array_name;

//allocate memory
array_name = new dataType[size]

Using the 'new' keyword, you inform the compiler to allocate the memory for Array of type 'dataType' for provided size.

For example:-

int [] age = new int[10]; or,
String [] name = new String[10], or

Here age array can store up to 10 elements of type int, or the name array can keep a maximum of ten elements of type String.

Note:

a.The elements in the Array allocated by new will automatically be initialized to default value as follows:-

  • int - 0
  • double - 0.0
  • String - null
  • reference - null

b. Array always starts with 0th index, i.e., the first element of Array at index 0 c. If Array has size n, the last element is always at n-1 index.

How to initialize an Array

Initializing an Array means you are allocating the values at array indexes. You can initialize the Array through the below ways:-

a. Initialization during declaration: You can initialize the Array during declaration as below::

int [] age = {1,2,3,4,5,6}

Using this way, you don't need to provide the size of the Array. Instead, the compiler automatically detects the number of elements.

b. You can initialize the values at index as below:-

int [] age = new int[5];
age[0] = 1;
age[1] = 1;
age[2] = 1;
age[3] = 1;
age[4] = 1;

How Array stored in memory

In Java, arrays are objects; therefore, just like other objects, arrays are stored in heap area. An array stores primitive data types or reference (to derived data) types. Just like objects, the variable of the Array holds the reference to the Array.

How to access an Array elements

We can access the element of an array using the index number of an array as below:-

array[index]

Using above mentioned way, you can access an element at provided index.

What if we want to read all elements of an Array?

To read all elements of an Array, we can use loops that iterate each element starting from 0 till n-1; n is the number of elements.

private void traverseArray() {
    int[] number = { 1, 2, 3, 4};
    // using for loop, traverse index by index
    for (int i = 0; i < number.length; i++) {
        System.out.println("Number: " + number[i]);
    }
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4

In the above example, did you notice the ` age.length? This array property provides the number of elements or size of an array.

Let's use the foreach loop or enhanced for loop to access the array elements introduced in JDK 1.5, enabling you to traverse the complete Array sequentially without using an index variable.

private void traverseArray() {
    int[] number = { 1, 2, 3, 4};
    // using foreach loop
    for (int i : number) {
            System.out.println("Number: " + i);
        }
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4

You might wonder what happens when we try to access elements out of array size.

JVM throws an ArrayIndexOutOfBoundsException to indicate that you are trying to access the illegal index.

int[] age = { 1, 2 };
// here loop trying to access index 3
// which is greater than the size of an array
for (int i = 0; i < age.length + 1; i++) {
    System.out.println("Age: " + age[i]);
}

Below exception will be thrown if you try to access an index greater than the size of an array or not available in Array.

java.lang.ArrayIndexOutOfBoundsException: 2
    at com.dsa.practice.array.fundamentals.ArrayFundamentals.arrayException(ArrayFundamentals.java:62)

Passing an Array to the method

You can pass the Array of any type as an argument to the method as the other variables or objects. For example

private void displayNumber(int[] number) {
   for (int i = 0; i < number.length; i++) {
      System.out.print(number[i] + " ");
   }
}

You can invoke the method by passing the Array as an argument below, which displays the number on the console.

classObject.displayNumber(number);

Returning the Array from the method

A method can also return an array just like a method returns any variables or objects as below.

private int[] number(int[] number) {
   int[] array = new int[number.length];

   for (int i = 0, j = array.length - 1; i < array.length; i++, j--) {
      array[j] = number[i];
   }
   return array;
}

Important points about Arrays

  • The size of Array must be defined as int or short, not long
  • Java array can be also be used as a static field, a local variable, or a method parameter
  • All arrays are dynamically allocated in the memory but contiguous
  • The Direct superclass of Array is Object
  • Every array type implements Cloneable and Serializable interface
  • if you try to call the getClass() of Array following values will be returned
      - class [I - For int type array
      - class [B - For byte type array
      - class [S - For short type array
      - class [Ljava.lang.String; - For String type array
    
  • The array length can be positive or zero; it can never be negative. Therefore, the length field of Array is always the final field.

Array Practice Problems

Below few problems are listed you can use for a practice whose source code is available at GitHub

Easy Problems

Medium Problems

Conclusion:-

I hope you found this tutorial insightful and helpful. If so, please like and follow!

Did you find this article valuable?

Support Himanshu's Blog by becoming a sponsor. Any amount is appreciated!