Wednesday, March 2, 2022

Array in Java With Examples

An array in Java is a container object that holds values of a single type. These elements are stored in a contiguous memory location and referred by a common name. Note that this common name (variable) is an object which holds reference to the array.


Pictorial representation of an Array in Java

Let’s say you have an array numArr of length 10 and numArr is of type int. That means numArr is a variable that references the memory allocated for this int array.

array in java

Important points about array in Java

  1. Array holds a fixed number of elements.
  2. Length of an array is specified when an array is created. Once length of an array is specified it remains fixed.
  3. Array in Java is index based and the index starts from 0. So the first element is stored in the array at index 0.

Types of array

Array in Java can be of single dimension (one dimensional) or multi dimensional. So there are two types of arrays-

  • Single dimensional– It is essentially a sequence of elements of similar types.
  • Multi dimensional– It is essentially an array of arrays, in one dimensional array there is one row with multiple columns where as in multi-dimensional array there are multiple rows with multiple columns.

Java Array declaration and initialization

To declare an array in Java you have to provide array’s type and array’s name. An array’s type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array.

As example; if you want to declare an array, numArr of type int, it can be done as-

 int[] numArr;

here int denotes the type and numArr is the name of the array.

You can also place the brackets after the array name so this is also right-

 int numArr[];

But Java doc says “However, convention discourages this form; the brackets identify the array type and should appear with the type designation.” So let’s stick to type[] arrayName form.

Note that declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

In order to create an array in Java you can use one of the following options-

  1. Creating array using new operator.
  2. Initializing array while it is declared.

Creating array in Java using new operator

General form of creating an array (in case of single dimensional array) using new operator is as follows-

arrayName = new type[size]

Here,

  • type– Specifies the type of the data.
  • size– Specifies the number of elements in an array.
  • arrayName– array variable that holds reference to the created array.

As example-

int[] numArr; // array declared
numArr = new int[10]; // array created

When the above array is created using new operator, memory for 10 int elements is allocated and the array variable numArr holds the reference to that memory.

Of course you can combine these two steps into one to make it more compact and readable-

int[] numArr = new int[10];

One important thing to note here is that the array created by using new operator will automatically initialize its elements to the default value, which is-

  1. 0 for numeric types.
  2. false for boolean.
  3. null for an array of class objects.

As example– If you have created an array which holds element of type int and print all the values just after creating it you will get all values as zeroes.

public class ArrayDemo {
  public static void main(String[] args) {
    int[] numArr = new int[10];
    for(int i = 0; i < numArr.length; i++){
      System.out.println("Value at index " + i + " is " + numArr[i]);
    }
  }
}

Output

Value at index 0 is 0
Value at index 1 is 0
Value at index 2 is 0
Value at index 3 is 0
Value at index 4 is 0
Value at index 5 is 0
Value at index 6 is 0
Value at index 7 is 0
Value at index 8 is 0
Value at index 9 is 0

Here few things to note are-

  1. As soon as array is created using new operator memory is allocated for all the elements (in this case 10).
  2. Since default for numeric type is zero so all the elements of the array have value zero.
  3. Array in Java is zero index based, which means, for array of length 10 start index is 0 and last index is 9.
  4. If you don't create an array and just declare it, then the compiler prints an error like the following, and compilation fails: Variable numArr may not have been initialized

Initializing array while it is declared

Another way to create and initialize an array in Java is to provide values in between the braces when the array is declared.

int[] numArr = {1, 2, 3, 4, 5};

Here the length of the array is determined by the number of values provided between braces and separated by commas.

How to access array elements in Java

You can access array elements using the array index which is 0 based i.e. first element of the array is at index 0.

public class ArrayIndex {
 public static void main(String[] args) {
  int[] numArr = new int[5];
  // 4th element of the array
  numArr[3] = 7;
  // 1st element
  numArr[0] = 9;
  
  for(int i = 0; i < numArr.length; i++){
   System.out.println("Value at index " + i + " is " + numArr[i]);
  }
 }
}

Output

Value at index 0 is 9
Value at index 1 is 0
Value at index 2 is 0
Value at index 3 is 7
Value at index 4 is 0

Java run-time array index check

Java has strict run-time check for any out of range index. For example if the length of the array is 10 then the index range for the array is 0-9. Any attempt to use index out of this range, either negative number or positive number, will result in a run-time exception ArrayIndexOutOfBoundsException.

public class ArrayIndex {
 public static void main(String[] args) {
  int[] numArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  //results in error (index is 0-9)
  int value = numArr[10];
 }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
 at org.netjs.examples1.ArrayIndex.main(ArrayIndex.java:8)

Array of objects in Java

You can also create an array of objects. As already mentioned above, at the time of creation of an array of objects, all the elements will be initialized as null for an array of class objects. What that means for each element of an array of object you will have to provide the object reference too.

As example-

Employee[] empArr = new Employee[10]; // array creation
Employee emp = new Employee();
empArr[0] = emp; // object reference

Multi-dimensional arrays in Java

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets. As example, if you want to create a 2-D array of String called names-

String[][] names. 

Each element, therefore, must be accessed by a corresponding number of index values.

Multi-dimensional array Java Example

public class ArrayDemo {
  public static void main(String[] args) {
    int[][] numArr = new int[3][3];
    // providing values for array
    for(int i = 0; i < 3; i++){
      for(int j = 0; j < 3; j++){
        numArr[i][j] = i + j;
      }
    }
    // Displaying array elements
    for(int i = 0; i < 3; i++){
      for(int j = 0; j < 3; j++){
        System.out.print(" " + numArr[i][j]);
      }
      System.out.println();
    }       
  }
}

Output

 0 1 2
 1 2 3
 2 3 4
 

That's all for this topic Array in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Package in Java
  2. Access Modifiers in Java - Public, Private, Protected and Default
  3. Find Duplicate Elements in an Array Java Program
  4. Find Largest and Second Largest Number in Given Array Java Program
  5. Matrix Multiplication Java Program

You may also like-

  1. String in Java Tutorial
  2. Association, Aggregation and Composition in Java
  3. Initializer Block in Java
  4. Lambda Expression Examples in Java
  5. Effectively Final in Java 8
  6. Deadlock in Java Multi-Threading
  7. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  8. Difference Between Checked And Unchecked Exceptions in Java

No comments:

Post a Comment