Please wait ......

Arrays In Java

Learn about the need for Arrays. Also a brief overview of Arrays in Java.


In the previous chapters we learnt about data types in Java.

Let us assume we need to declare variables to store the weight of students (in kilograms) in a class. We knew there are 15 students in a class. We would tend to declare the variables as below.

  public static void main(String[] args) {
        short weightOfStudent1 = 50;
        short weightOfStudent2 = 54;
        short weightOfStudent3 = 66;
        short weightOfStudent4 = 52;
        short weightOfStudent5 = 48;
        short weightOfStudent6 = 50;
        short weightOfStudent7 = 54;
        short weightOfStudent8 = 66;
        short weightOfStudent9 = 72;
        short weightOfStudent10 = 56;
        short weightOfStudent11 = 50;
        short weightOfStudent12 = 44;
        short weightOfStudent13 = 61;
        short weightOfStudent14 = 51;
        short weightOfStudent15 = 49;
    }

So whats the problem in the above declaration?

Problem Statement: We do not know how to declare when the number of students is passed as an input to the program.  There can be 15 students or there can be 35 students. As we need to declare all these variables during compile time, we have a problem in hand to solve.

Introducing Arrays:

The above variables to denote students weight can be declared using Arrays as below.

    public static void main(String[] args) {
       short[] weightOfStudents=new short[]{50,54,66,52,48,50,54,66,72,56,50,44,61,51,49};
    }

So how to declare an Array when the number of students is passed as input ? We do it as below.

    public static void main(String[] args) {
        int numberOfStudents = Integer.parseInt(args[0]);
        short[] weightOfStudents = new short[numberOfStudents];
    }

Now assume rather than the number of students, the weight of students is passed as input to the program, here is how we will assign the values to the Array.

    public static void main(String[] args) {
        int numberOfStudents = args.length;
        short[] weightOfStudents = new short[numberOfStudents];
        
        for(int counter=0;counter < numberOfStudents;counter++){
            weightOfStudents[counter]=Short.parseShort(args[counter]);
        }
    }

 

Remember the position of an element in Array starts from zero.

Watch the video showing the complete workflow below.