Introduction to Arrays

In this guide, we will learn about arrays. An array is a named collection of contiguous storage locations that are next to each other that contain data items of the same type.

Arrays offer a more streamlined way to store data than using individual data items for each variable. Arrays also allow you to work with their data more efficiently than with data stored in individual variables.

Why we need Arrays?

Let’s see why. Suppose you want to create a program that has 26 options, one for each letter of the alphabet. One way would be to declare a separate char variable for each letter of the alphabet:

char alphabet1;
char alphabet2;
...
char alphabet26;

Obviously, requiring 26 separate variables for this problem is tedious and inconvenient. Similarly, to instantiate and assign a value would require 26 statements:

char alphabet1 = 'A';
char alphabet2 = 'B' ;
...
char alphabet26 = 'C';

This approach is also tedious. What we need is some way to use a loop to process each variable, using a loop counter, k, to refer to the kth char on each iteration of the loop. An array lets us do that. For example, the following code will declare an array for storing 26 char and then instantiate each variable:

char letter[]  = new char[26]; 

for (int k = 0; k < 26; k++) {
    letter[k] = new char("A");
}

Note: Avoid using char datatype in Java if you are working with Unicode characters.

you can see how efficient this is. It uses just a few lines of code to do what would have otherwise required 50 or 60 lines of code without arrays. In this guide, we’ll see how to use one-, two- and three-dimensional arrays. We also study sorting and searching algorithms to process arrays.


Licenses and Attributions


Speak Your Mind

-->