Arrays and their behaviour in java

When I was new to programming with java i was afraid of arrays but now its my every hour's work to play around with them. Java array are real flexible and useful this article will take you through them.

Arrays are the container variables which can contain more than one values, usually of similar type. As Java is strongly typed language so in Java arrays store same type of values in it. you can create any type of array in Java forming from the basic primitive data types and also the Class objects.

Declaring array is as simple as declaring the variables. You can declare an integer array as

int[] name;

opposite to other languages in Java the [] is used with the type declaration rather than name because that specifies the type of elements that are stored in it.

you initialise the array by using "new" keyword. like this.

int[] name = new int[5]; //declaring an array which can store 5 integers.

You can create array for any type of elements. Java also supports the multi dimensional arrays, and that too is not difficult to create. Same syntax would do it.

int[][] name new int[3][5]; //this creates a 3x5 2D array

Inserting elements in array is simple like creating them. you just have to assign a value at the index. But be warned the index starts at 0 not 1.

name[0] = 0;

name[1] =  1;

name[2] = 2;

name[3] = 3;

name[4] = 4;

This assigned 5 values to 5 array position, to access these elements you need to access their index.

System.out.println(name[0]); //prints value at 0 index in array, i.e. 0

You can also assign values in array in alternative way

name[] = {1,2,3,4,5}; //assign values to array

name[][] = {{1,2,3},{1,2,3}}; //assign values to 2d array

java also provides the option for creating uneven array matrix, that is known as jagged array

name[][] = {{1},{1,2},{1,2,3}}; //see there is different number of element in each row of this array, this type of array is known as jagged array

NOTE: if you want to learn the arrays please don't only read them, Practice! yes this is the key to understanding.