Array is a collection of variables or its a bunch of memory locations, you can say in simple word. Array is a very basic data structure, can have multiple locations or memory slots where we can keep our data. For example if create an integer variable, you can keep one number in it. But what if want to store 5 or 20 or 100 different numbers. Answers is the array. Array has a fixed size, it means if you have declared an array of size 100, you can change it to any other size after creation. We use a number called "index of array" to access different elements or members of the array. This index starts from 0, so in we want to use 3rd element of the array, we will use index value 2. The each location is one element of the array. So lets see how to declare an array.
There are few ways to declare an array.
int[] myArray;
int myArray[];
int myArray[] = new int[4];
you can give the size of array in brackets as I did in third example, or leave it open and define the size later like this.
int myArray[];
myArray[] = 12,33,544,71;
This array will now confirmed as 4 location array.
Now if you want to use array elements in your program, you can use following method.
System.out.println(myArray[2]);
This will print the third element of the array on screen. But what if want to print 1000 elements of the array. Would you write 1000 lines of System.out.println. No we will use for loop as follows.
for(int i = 0; i < 1000; i++)
{
System.out.println(myArray[i]);
}
Same technique can be used to put data in array. You must do the exercise yourself for better learning.
Array has a drawback of having fixed size. In next lectures we will discuss some other data structures that can be re sized. So stay with us.
No comments:
Post a Comment