what is an array?

what is an array?

As we already know that variable are used to store and manipulate the data in JAVA program.Often single or few variables are enough to handle some sort of programming to resolve the problem But there are situation arises where we need to store the list of names of 100 student who got A grade
in their annual examination. We can handle this situation by declaring 100 variables line name0 name1name2, name3....name99 with data types string. Clearly this situation becomes tedious  and
co-cumbersome.

In such a situation special data structure called the Array comes into play to handle the situation in
JAVA program. An ARRAY is a special data structure which holds and manipulates a fixed number of values same data type. In other words an array is data structure or container or collection of fixed number of variables which has same data type.

An array has two main properties, all the items or elements in an array has same data type and an array always has fixed length. One shortcoming of the array is that it cannot hold different data types. Each item in an array is called an element, and each element is accessed by its numerical index

When are is declared in the program it create or reserve the fixed number of memory locations for storing the values or data. These memory locations in an array are called items or elements of the array. Each element in array is accessed by its index values as illustrated in the below figure.



Declaring an array


In JAVA program an array is declared as below

dataType[] array_name;

Where dataType is any kind of data type such as int,string,float or it may be of type object.
and array name is a variable name just like other variable names.

int[] anarray;
string[] studentname; 

 The previous examples create arrays, but they do not store any values in them. To do this, you can use the new keyword along with the variable type or store values in the array within { and } marks. When using new, you must specify how many different items are stored in the array. Each item in an array is called an element. The following statement creates an array and sets aside space for the values that it holds:

 int[] integerarray = new int[50]

String[] StudentName = new String[50];

This example creates an array of Strings called StudentName. The array has 50 elements that can store the names of 50 students who got A grade in their annual examination.

When you create an array with the new statement, you must specify the number of elements. Each element of the array is given an initial value that depends on the type of the array. All numeric arrays have the initial value 0, char arrays equal ‘\0’, and boolean arrays have the value false.

 A String array and all other objects are created with the initial value of null. For arrays that are not extremely large, you can set up their initial values at the same time that you create them. The following example creates an array of strings and gives them initial values:


String[] reindeerNames = { “Dasher”, “Dancer”, “Prancer”, “Vixen”,“Comet”, “Cupid”, “Donder”, “Blitzen” };


How to Access and Element of array.


An element of the array is accessed using arrayname followed by an index values inside the squre brackets.

For examples

StudentName[1];
StudentName[2];

Similary

integerArray[0]
integerArray[1]

Below super simple program demonstrates how arrays are declared, initialized, assigned  some values to its elements an then accessed.




Please note that the first index values of the first element of an array is started with the value of 0. It means that the range of index is from 0 to one less than the length of array. Such as in above program
first element of the array is StudentName[0] and last element of the array is StudentName[4].

What happen if an element out side the range the accessed inadvertently the program generate out of bound exception like this.

 


Declaring a Variable to Refer to an Array


The preceding program declares an array (named anArray) with the following line of code:

// declares an array of integers
  int[] anArray;

Like declarations for variables of other types, an array declaration has two components: the array's type and the 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. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the brackets after the array's name:

// this form is discouraged
float anArrayOfFloats[];

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.Creating, Initializing, and Accessing an Array

One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

// create an array of integers
anArray = new int[10];

If this statement is missing, then the compiler prints an error like the following, and compilation fails:

ArrayDemo.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = {
    100, 200, 300,
    400, 500, 600,
    700, 800, 900, 1000
};

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

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        };
        // Mr. Smith
        System.out.println(names[0][0] + names[1][0]);
        // Ms. Jones
        System.out.println(names[0][2] + names[1][1]);
    }
}

The output from this program is:

Mr. Smith
Ms. Jones

Finally, you can use the built-in length property to determine the size of any array. The following code prints the array's size to standard output:

 System.out.println(anArray.length);

Copying Arrays

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src, int srcPos,
                             Object dest, int destPos, int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated." It uses the System.arraycopy method to copy a subsequence of array components into a second array:


class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
                'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

The output from this program is:

caffein

Array Manipulations

Arrays are a powerful and useful concept used in programming. Java SE provides methods to perform some of the most common manipulations related to arrays. For instance, the ArrayCopyDemo example uses the arraycopy method of the System class instead of manually iterating through the elements of the source array and placing each one into the destination array. This is performed behind the scenes, enabling the developer to use just one line of code to call the method.

For your convenience, Java SE provides several methods for performing array manipulations (common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class. For instance, the previous example can be modified to use the copyOfRange method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference is that using the copyOfRange method does not require you to create the destination array before calling the method, because the destination array is returned by the method:


class ArrayCopyOfDemo {
    public static void main(String[] args) {
       
        char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',
            'i', 'n', 'a', 't', 'e', 'd'};
           
        char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
       
        System.out.println(new String(copyTo));
    }
}

As you can see, the output from this program is the same (caffein), although it requires fewer lines of code. Note that the second parameter of the copyOfRange method is the initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively. In this example, the range to be copied does not include the array element at index 9 (which contains the character a).

Some other useful operations provided by methods in the java.util.Arrays class, are:

    Searching an array for a specific value to get the index at which it is placed (the binarySearch method).
    Comparing two arrays to determine if they are equal or not (the equals method).
    Filling an array to place a specific value at each index (the fill method).
    Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.


Multidimensional Arrays

The arrays thus far in the hour all have one dimension, so you can retrieve an element using a single number. Some types of information require more dimensions to store adequately as arrays, such as points in an (x,y) coordinate system. One dimension of the array could store the x coordinate, and
the other dimension could store the y coordinate.

To create an array that has two dimensions, you must use an additional set of square brackets when creating and using the array, as in these statements:

boolean[][] selectedPoint = new boolean[50][50];
selectedPoint[4][13] = true;
selectedPoint[7][6] = true;
selectedPoint[11][22] = true;



This example creates an array of Boolean values called selectedPoint. The array has 50 elements in its first dimension and 50 elements in its second dimension, so 2,500 individual array elements can hold values (50 multiplied by 50). When the array is created, each element is given the default
value of false. Three elements are given the value true: a point at the (x,y) position of 4,13, one at 7,6, and one at 11,22. Arrays can have as many dimensions as you need, but keep in mind that they take up a lot of memory if they’re extremely large. Creating the 50 by 50 selectedPoint array was equivalent to creating 2,500 individual variables.