Arrays (Lesson-19)

An array is a collection of variables of the same DataType. You use array to store many things of the same kind. For example, if you want to store a list of numbers, you can use an int array. Arrays are defined in the following format:

DataType[ ] arrayName ;

For example, to define an int array, you would use:

int[ ] array;

Defining the capacity of an array:
You can define the capacity of an array right at the time of its creation. It takes the following format:

DataType[ ] arrayName = new DataType[capacity] ;

The keyword “new” is new to you and it is used to create new things. In this case, we created a new array with it. Keeping in mind the above format, to define an int array of capacity 10, we would use:

int[ ] array = new int[10] ;

You cam also define arrays first and declare their capacity later:

int[ ] array ;
array = new int[10] ;

Storing the values in an array:
You store the values in an array in the following format:

arrayName[index] = value ;

For example, we created an int array named “array” above. To store a value at its 5th index position we would use:

array[5] = 100 ;

The index of an array starts from zero. So an array with a capacity 3 will have following indices (plural of index) 0,1,2
Similarly, an array with capacity 10 will have indices from 0 to 9.

Consider the following code to create an int array with capacity 5 and store some values in it.

Initializing an array:
You can also initialize an array right at the time of its creation. For example, consider an array of String being initialized:

String[ ] s = { “I like” , “Java” , “programming” , “hello world” };

Instead of “new String[capacity]” , you put the values in curly brackets { } separated by comma. In this way you can initialize an array right at the time of its creation. Similarly, initializing an int array looks like this:

int[ ] i = { 23 , 45 , 67 , 78 } ;

When you initialize an array like this, there is no need to set the capacity of it. It is set automatically. The above line of code will declare an int array of capacity 4 and initialize it.
Let’s take a last example:

Look at the above example. You will access the values of an array in the same way you stored them.
For example:
int i = array[4];

Leave a Comment