Wednesday, March 21, 2018

Arrays in java

Another pretty important component in Java programming is the use of Arrays. Like variables and loops, most of the program you will write will make use of them.
An Array can be defined as an data type that holds a collection of of a similar data type. with having consecutive memory allocation.

Before more further let see previous post of series
  1. Making Games With Java- Introduction
  2. Getting Everything you need for Java
  3. Introduction to Java Programming
  4. Basic data types and Variables in java
  5. Basic Data types and Variables in java - Continued...
  6. User Input using Scanner class in java
  7. Conditional Logic in java
  8. Loops in java

What are arrays used for?

There are two main uses of arrays:
  •     Conecutive Memory Allocation
  •     Easy Data access ( as index fetch )
Now consider this: you have to create the programme that finds the average age of thirty people. You can do this in two ways. You could:
  1. Create 30 separate age variables (age1, age2… age30) and define values for each of them one by one, before actually calculating the average. This is very inefficient, tedious, and will make the code unnecessarily lengthy.
  2. Or you could store all thirty age values into a single Integer array, which you could call something like ‘Age’. Not only will this be less stressful, it also makes it easier to access data through the array index.
Arrays in Java are index-based i.e. elements stored in array are accessed through their index values. And array indices also start from 0. Therefore, the first element is stored at 0, the second at 1, etc.
Is there a con to arrays?
  • The major disadvantage to arrays is that they can only contain a fixed number of elements, which cannot be changed at runtime.
  • You need to declare the size of the array at the compile time only.
Declaring Arrays.
Array and variable declaration have the same basic principle. You state the data type you want to use with the array (int, char, float, etc.), you give the array a name and save the value into it. The main difference is the addition of square brackets ([]), which is basically the universal coding symbol for arrays.
Below, I have created an integer array variable named arrayInt:
int arrayInt [] ;
You can see that it looks like a basic integer variable, with the addition of the square brackets to the end of variable name.
Note, the square bracket can be added to the back of the data type instead of the variable name, like so this is also valid declaration.
int [] arrayInt ;

Also take note that in the naming of arrays, the rules that apply to naming of variables apply. If you’re not sure what they are, please click this link. You can also turn any data type into an array. You can create a String array:
String arrayString [];
… a Float array:
float arrayFloat [];
… and even a Boolean array:
boolean arrayBool [];
But we don’t know how many values can be saved into the arrays yet. To set this, in the integer array for example, go to the next line and type this in:
arrayInt = new int [5];
According to the code above, this array has a limit of five values. It will not accept or recognise any more values after the fifth.
You can also declare the array limit on the same line where you declared the array:
int[] arrayInt = new int[5];
So now we’ve created an integer array called ‘arrayInt’, that can hold up to five integer values.  Now that we’ve set the array, the system will assign default values of zero to all array positions.
Now, assign values 1 to 5 in each array position:
arrayInt [0] = 1;
arrayInt [1] = 2;
arrayInt[2] = 3;
arrayInt[3] = 4
arrayInt[4] = 5;    
Now, we’ve assigned values to each and every memory space in the array, and we’ve set a print statement to print out the third value (the value with the memory space [2]. The code in your coding window should look a lot like this:
Now run your programme, it means your output was this:
But if you’re like me, and would rather do everything one line, you could just as well do this:
int [] arrayInt = {1, 2, 3, 4, 5};
Note, you don’t have to specify the number in the square bracket. The number of values you set will automatically be the set as the array limit.
You probably also noticed that you no longer needed to use the new keyword, or repeat the data type, or put another square bracket. Let me warn that this will only work in the case of int, String and char values. You can do this:
char [] arrayChar = {'A', 'B', 'C', 'D'};
…or this:
String [] arrayString = {"My", "name", "is", "Vishal"};
But not this:
boolean [] arrayBool = {true, false, false, true};
For that, you’d have to do this:
Boolean [] arrayBool = new Boolean [] {true, false, false, true};

Arrays and Loops

If there’s anything that arrays work well with, it’s loops. In fact, any program that uses arrays would most likely make use of loops, and loops can also be used interchangeably with arrays.
Let’s take the integer array we made earlier and join it with a loop. Remove the print statement and replace it with this for loop:
for(int i = 0; i < arrayInt.length; i++){
Run it and it will count every number in the integer array, from 1 to 5, like this:
Another thing you can do with loops and array is use a loop to set values to your array. I mean, in the beginning, I said that we could assign values to the array by doing this:
arrayInt[2] = 3;
But this would be tedious for assigning values to, let’s say, thirty values or more. Like now, instead of just typing a long list of variables and values repetitively, we could just as easily use a loop. Comment out everything you’ve done so far and type this down:
int[] arrayInt = new int[30];
for(int i = 0; i < arrayInt.length; i++){
arrayInt[i] = i + 1;
Then run it, and your result should be this:
I enlarged my output table to show all the values. You can do this by holding your cursor over the output window until you see the arrow pointing up and down, then drag up.
Multi-Dimensional Arrays
So far, the arrays we’ve been looking at are one-dimensional (they can only take one column of data). But you can set up arrays that hold data in rows and columns; kind of like a matrix.
These arrays are called Multi-Dimensional Arrays. They are declared the same way as one-dimensional arrays, except they have two square brackets instead of one:
int [] [] arrayInt = new int [4] [4];
The first square bracket shows the number of rows in the array while the second shows the number of columns. 
The above array has four rows and four columns.

Assigning values to Multi-Dimensional Arrays
To assign values to a multi-dimensional array, you must specify the row and column numbers you want the value to be saved in. For instance:
arrayInt [0][0] = 1;
arrayInt[0][1] = 2;
arrayInt[0][2] = 3;
arrayInt[0][3] = 4;
The first row is 0, so every value is assigned to that row. 
The columns count from 0 to 3, which is four values. To fill the second row, you would have to change the value in the first brackets from 0 to 1, leaving the column values the same.
Continue adding values until you’ve filled every row and column. When you’re done, you should have something like this:
Now normally, before we printed out every value in an array, we would use a for loop. That is the same case in multi-dimensional array, except in this case, you’ll need two for loops. One for the rows, and the other for columns.
Quickly add these lines to your code:
So, the two loops are set to run until their values reach the limits of our rows and columns, printing out our values as thus:

Now if we see the full Program of array 

package tutorialproject;

public class Arrays {

    public static void main(String[] args) {
        int[][] arrayInt = new int [4][4];
            arrayInt[0][0] = 1;
            arrayInt[0][1] = 2;
            arrayInt[0][2] = 3;
            arrayInt[0][3] = 4;

            arrayInt[1][0] = 5;
            arrayInt[1][1] = 6;
            arrayInt[1][2] = 7;
            arrayInt[1][3] = 8;
            arrayInt[2][0] = 9;
            arrayInt[2][1] = 10;
            arrayInt[2][2] = 11;
            arrayInt[2][3] = 12;
            arrayInt[3][0] = 13;
            arrayInt[3][1] = 14;
            arrayInt[3][2] = 15;
            arrayInt[3][3] = 16;
            int rows = 4;
            int columns = 4;
            int i, j;
            for(i = 0; i < rows; i++){
                for(j = 0; j < columns; j++){
                    System.out.print(arrayInt[i][j] + " ");

I hope you have learned something in this post , if you liked it please share it with your friends and colleagues ,

Happy learning


Post a Comment