by Dinesh Thakur Category: array

Arrays Definition: Perhaps one of the most important of all concepts that you need to learn to be effective is the array. Until now, we have looked at variables that hold just one value – the ints hold one number and the strings hold one text string. Arrays are used when we want to hold two or more values, perhaps a list. Arrays can be thought as columns in a spreadsheet – a spreadsheet can have one, or it can have many columns.  

Similar to the spreadsheet, each row in an array has a position number; these begin at 0 and go up for each position that has a value. Setting up an array requires that you inform Java what type of data is being stored in it – strings, Booleans, integers,  and so on. Then you need to tell Java the number of positions in the array and do  this to set them up:

There is only one difference between setting up an int variable, and an array – the data type in an array is followed by square brackets []. These brackets are enough for Java to know that an array is being set up.

For example, To sort, maintain and display the marks of 80 students in a class, we need to declare 80 integer variables each of which holds the marks of a particular student. It is complicated to make and handle such a program that declares 80 int type variables, assign values to them and compare each against the other to do the sorting. The problem worsens if we have 1000 students. However, these types of problems can be simplified using arrays.

An array is a collection of logically related variables (similar elements) of the identical data type that share a common name. The array is a predefined class present in java.1ang package. It is a final class which can't be inherited. It is used to handle a large amount of data, without the need to declare many individual variables separately. The array elements are stored in a contiguous memory location (i.e. one after the other). All the array elements must be either of any primitive types like int, float, char, double, etc. or they can be of any object references type like class.
Each array element is accessed and manipulated using an array name followed by a unique index or subscript that specify the position within the array. A single subscript is required to access an element of the one-dimensional array, and two subscripts are required to access an element of the two-dimensional array. All the arrays whose elements are accessed using two or more subscript are called multidimensional arrays. It should be kept in mind that each subscript is enclosed in square brackets and it should be expressed as a non-negative integer constant or expression. The primary advantage of an array is that it organises data in such a way that it can be manipulated. So if an array containing marks of students is given, then we can easily calculate the average marks scored by the students.

The concept of an array that helps us to store a group of values under a single name and refer directly to a particular value makes the programs very simple and efficient. This concept is present in almost all programming languages including C, c++ and Java.

Creating Array

Unlike other languages like C/C++, arrays in Java are implemented as objects. So to create and use an array, you have first to declare the array and then instantiate it using the new operator.

Declaring an Array

Before you can use an array, you must first declare a variable to reference an array and specify the type of array the variable can reference. The syntax for declaring a one-dimensional array is

arrayRefVar = new datatype[size];

Start with the array name with an equals sign afterward. Then come the new keyword and the data type, followed by the square brackets. In those brackets is the size of the array – the number of positions it has. All of this can go on a single  line: 
Here data type is any primitive data type or reference type. It determines the data type of each element in the array. An empty set of square brackets ([]) indicates that an array reference variable arrayRefVar holds a one-dimensional array. The arrayRefVar follows the same rules and conventions as that of identifiers.

declares an array reference variable named numthat can store a reference for an integer array.

For example, the declaration declares an array reference variable named num that can store a reference for an integer array. No memory has been yet allocated to hold an array at this time, so the value of the reference variable is null. An alternative notation for declaring the above array is
int num[];
It only differs from the previous one in the placement of the square brackets. This style came from the C language and was adopted in Java to accommodate C programmers.
You can also declare multiple arrays of the same data type in one statement by inserting a comma after each array name. For example.
int [] min,max;
This statement declares min and max array variables that can store reference for integer arrays.

Instantiating an Array

Once you have declared an array reference variable, the next step is to create an array object and assign the reference of the newly created array to the existing array reference variable, using the following syntax,
arrayRefVar = new datatype[size];
Where arrayRefVar is the name of an existing array reference variable that stores the reference of the newly created array. The new keyword allocates memory for the array and size is an expression that evaluates to a positive integer and specifies the number of elements in the array. For example, the statement
num = new int[5];

create an array object and assign the reference of the newly created array to the existing array reference variable,creates an array of 5 elements of int type and assigns its reference to the array reference variable num.
You can combine the declaration of array variable with instantiation in a single line using the statement,
int[] num = new int[5];
This statement declares an array reference variable num, creates an array of 5 elements of int type and assign its reference to the array reference variable num.
When an array is created like this, its elements are automatically initialised to their default values. The default values are 0 in case of an array of numeric elements, false for boolean arrays, '\u0000'(space) for char arrays and null for an array of class type.
Now let us consider some more examples.
double[] dailyTemp = new double[365];
dailyTemp is an array variable that stores the reference to the array containing 365 double type values.
float[] salaries = new float[100];
salaries is an array variable that stores the reference to the array containing 100 float type values.
Student[] s = new Student[20];
s is an array variable that stores reference to the array of 20 Student objects.

Accessing Array Elements

Once the array is created, you can access an array element by using the name of the array followed by an index enclosed between a pair of square brackets. The index or subscript of an array indicates the position of an element in the array. The index of the first element in the array is always 0 (zero), the second element has an index I and so on. The index of the last element is always one less than the number of elements in the array. The syntax for accessing an array element is
arrayRefVar[index];
Here, the index is an integer literal or an expression that evaluates to an int.
In our example, the first element of the array is num [0], the second element is num [1], and the last element is num [4].
NOTE: An index must be an int value or a value of a type that can be promoted to int such as byte, short or char. You are using a value of type long as an array index result in compile time error. One should make sure that array indexes must be between 0 and the number of elements minus 1. Attempting to access an element of an array using an index less than 0 or higher than the index value for the last element in the array will compile without errors but will generate an ArraylndexOutOfBoundsException at run time.
Similarly, to assign a value to an element of a one-dimensional array, use the following syntax
arrayRefVar[index] = value;
For example, to assign a value 15 to an element at index 2, you need to write
num[2] = 15;
Now let us consider a program that demonstrates how to assign values to array elements and then access it.

publicclass ArrayAccessDemo {
   publicstaticvoid main(String[] args){
        int[] num =newint[5];
        num[0]=5;
        num[1]=15;
        num[2]=25;
        num[3]=30;
        num[4]=50;
        System.out.println("Array Element num[0] = "+ num[0]);
        System.out.println("Array Element num[1] = "+ num[1]);
        System.out.println("Array Element num[2] = "+ num[2]);
        System.out.println("Array Element num[3] = "+ num[3]);
        System.out.println("Array Element num[4] = "+ num[4]);
     }
}
Output :
Array Element num [0] 5
Array Element num [1] 15
Array Element num [2] 25
Array Element num [3] 30
Array Element num [4] 50
assign values to array elements
 Now let us consider another program that input the elements of an array and prints its contents.
//input and access array elements
import java.util.Scanner;//program uses Scanner class
publicclass ArrayDemo {
   publicstaticvoid main(String[] args){
       int[] numArray =newint[5];
       int i;
       //Create Scanner object to obtain input from keyboard
       Scanner input =newScanner(System.in);
       System.out.println("Enter the array elements ---->");
       for(i =0; i<5; i++)
            numarray[i]= input.nextInt();//Read number
       for(i =0; i<numArray.length; i++)
           System.out.println("Array element["+i +"] = "+numArray[i]);
    }
}

Explanation: This program inputs an array and prints its contents.
The statement,
int[] numArray = new int[5];
creates a numArray array variable that references an int-array containing 5 elements. We create a Scanner object to obtain an input from the keyboard. Finally, when all the input has been made it is printed.

Initialising Array

When an array is created, each element of the array is set to default initial value according to its type. However, it is also possible to provide value other than the default values to each element of the array.
This is made possible using array initialisation. Arrays can be initialised by providing values using a comma-separated list within curly braces following their declaration. The syntax for array initialization is
datatype[] arrayName = {value1, value2,........ };
For example : The statement
int[] num = {5,15,25,30,50};
creates a five element array with index values 0,1,2,3,4. The element num [0] is initialized to 5, num [1] is initialized to 15 and so on.
Note that we do not use the new keyword and do not specify the size of the array also. This is because when the compiler encounters such a statement, it counts the number of elements in the list to determine the size of the array and performs the task performed by the new operator. The initialising array is useful if you know the exact number and values of elements in an array at compile time.
The above initialisation statement is equivalent to

int[] num = new int[5];
num [0] = 5 ;
num [1] = 15;
num [2] = 25;
num [3] = 30;
num [4] = 40;
Similarly, you can initialize an array by providing objects in the list. For example
Rectangle[] rect = {new Rectangle(2,3),new Rectangle()};
It will create rect array of Rectangle objects containing 2 elements.
There is a variation of array initialization in which we use the new keyword explicitly but omit the array length as it is determined from the initializer list. For example:
int[] num = new int[]{5,15,25,30,50};
This form of initialization is useful if you need to declare an array in one location but populate it in another while still taking the advantage of array initialization. For example :
displayData(new String[]{"apple","orange","litchi"});
An unnamed array created in such a way is called anonymous arrays.
Now let us consider the following program that illustrates the use of initialization.

//Different ways of initializing Constructors
publicclass ArrayInitDemo {
  publicstaticvoid main(String[] args){//one way of initializing 1D array
  int[] num =newint[]{5,15,25,30,50};
  for(int i =0; i <num.length; i++)
     System.out.println("num["+i+"]="+num[i]);//second way of initializing 1D array
            display(newString[]{"apple","orange","litchi"});
   }
     staticvoid display(String[] str){
      for(int i =0; i<str.length;i++)
            System.out.println("str["+i+"] ="+str[i]);
     }
}
Output : num[0] = 5
num[l] = 15
num[2] = 25
num[3] = 30
num[4] = 50
str[0] = apple
str[l] = orange
str[2] = litchi

Getting length of an Array

After you create an array, you can access its length i.e. number of elements it holds. You can refer to the length of an array using its length field (which is implicitly public and final).A length field is associated with each array that has been instantiated.

Because length field is a public member so it can be directly accessed using the array name and a dot operator. Its syntax is
arrayRefVar.length
The length data field can be accessed using the dot operator. For example: To access the number of elements in an array named num, use the following syntax,
num.length
You can use the length field of an array to control a numerical for loop that iterates over the elements of an array.
for(int i=0; i<num.length; i++)
System.out.println("Element num[" + i + "] = " + num[i]);
Note: An array with length zero is said to be an empty array.
Now let us consider the following programs to explain it.

//Calculate average of 5 numbers
class Average {
   public static void main(String[] args) {
        int[] num = {10,20,30,40,50};
        int sum = 0;
        for(int i = 0; i<num.length; i++){
             sum += num[i];
        }
              double avg =(double)sum/num.length;
               System.out.println("average = "+avg);
   }
}
Output: average = 30.0
Explanation: The above program calculates the average of 5 numbers. The array containing 5 numbers can be referenced using the num_array variable. Here, we use num.length to get the length of the array referenced by num.
To calculate the average, we first add all the numbers in the array and then divide by the total numbers of elements. The result is then displayed.

Reusing Array Variables

Just like simple variables can store different values at different times, an array variable can also be used to store a reference to different arrays at different times. Suppose you have created and initialized array variable num using the following statement,
int[] num = {5,15,25,30,50};
Suppose later on you want to use the array variable num to refer to another array containing 6 elements of int type then you can do this by simply writing the statement,
num = new int[]{10,20,30,40,50,60};
On execution of this statement, the previous array of 5 int-type elements that is referenced by num is discarded and array variable num now references a new array of 6 values of type int.

Reusing Array Variables

//program showing reuse of array variable
public class ReuseArray {
   public static void main(String[] args) {
    int[] num = {5,15,25,30,50};
    System.out.println("Elements in orignal array --->");
    for(int i = 0;i<num.length; i++)
         System.out.print(num[i]+" ");
         System.out.println("\nElements in New array -->");
               num = new int[] {10,20,30,40,50,60};
               for (int i = 0;i<num.length;i++)
                     System.out.print(num[i]+" ");
    }
}
Output : Elements in original array :
5 15 25 30 50
Elements in New array :
10 20 30 40 50 60

Representation of array in memory

1. In java when the array is declared it captures a chunk of memory from the stack.
2. The array is constructed at the run time. At the construction time by specifying the size of the array through new operator garbage collector allocates consecutive memory location from the heap.
3. In java, the compiler implicitly calls the new operator to allocates memory from the heap for the creation of an array without using the new operator.
The Various types of Array those are provided by java as Follows:
1) Single Dimensional Array: These are Mostly used when we want to declare a number of Elements Single Dimensional arrays are used for Using Many elements, and they are Declared with Single Bracket Like int a [] etc. the Bracket will specify the size of array Elements Means how many array elements are declared and used For Accessing or using a variable we have to Specify the Index Value in the SubScript or Bracket of Array Variable.
The [] is used for dimensional or the sub-script of the array that is generally used for declaring the elements of the array For Accessing the Element from the array we can use the Subscript of the Array like this
a[3] = 100
So there is only the single bracket then it  is called as Single Dimensional Array
The Syntax For Declaring Array Elements in java is as follows-
int a[] = new int[5]
Note the new Keyword this is a Special Operator Which is used for Creating new Memory which is Continuous and The new Keyword is Also Creating For Memory For Number of elements That is Specified in Single bracket.

2) Two Dimensional Array: The Two Dimensional array Elements are used when we Wants to Perform the Operation in Matrix Forms the Two Dimensional arrays are used For Creating Matrix and  Displaying array elements in the Form of Rows and Columns The Total Elements of Arrays Will be Calculated by Multiplying the  Elements of Rows and Columns Like int a[3][3] i.e. 9 Elements will be used by Array These are Called as Two Dimensional Because they use two Brackets.
Like this int a[3][3]
So This is the Example of the Two Dimensional Array  In this first 3 represents the total number of Rows and the Second Elements Represents the Total number of Columns  The Total Number of elements are judge by Multiplying the Numbers of Rows * Number of Columns in The Array in the above array the Total Number of elements are 9
The Two Dimensional arrays are Declared as Follows:
int a[][] = new int[3][3].





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles