Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

e.g.

int value1 = 1;
int value2 = 2;
int value3 = 3;
int value4 = 4;
int value5 = 5;
int value6 = 6;

and instead you could just have

int[] values = {1,2,3,4,5,6};

This is example code of how to use arrays.

public class arraytest
{
       public static void main(String[] args)
       {
              // the main method passes in parameters from the console command line 
              // e.g. ./arraytest hi there, hi there are two parameters
              for (int i =0; i < args.length; i++)
              {
                     System.out.println(args[i]);
              }
 
              // to create a array of numbers
              int[] intarray = {0,2,3,4};
 
              for (int i =0 ; i < intarray.length; i++)
              {
                     System.out.println(intarray[i]);
              }
       }
}

After compiled the above code and executed the class file that would be generated by

Java arraytest hi there

The output of the program would be

hi
there
0
2
3
4

But if the console command line was empty then just the number values would be outputted since they are inserted into the code and the ‘hi there’ was inserted manually on the command line.

Leave a Reply

Your email address will not be published. Required fields are marked *