Wednesday, 1 February 2017

Array in Java

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.

Some important points about array

  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.

Pictorial representation of an Array

Let’s say you have an array numArr of length 10 and numArr is of type int.

array in java
Array in Java

Types of array

Array 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.

Array declaration and initialization

To declare an array 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 you can use new operator which is one of the way to create an array. It’s general form (in case of 1-D array) is -

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.

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

Another way to create and initialize an array 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.

Java run-time check

Java has strict run-time check for any out of range index. As example in numArr example used above 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.

Array of objects

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

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.

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. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Package in Java
  2. Access modifiers in Java
  3. Finding duplicate elements in an array - Java Program
  4. Generics in Java
  5. String in Java
  6. Matrix Multiplication Java Program

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment