JAVA

Arrays in Java

An array is a collection of variables of the same type. For instance, an array of int The variables in the array are ordered and each have an index. You will see how to index into an array later in this text.

Declaring an Array Variable in Java

A Java array variable is declared just like you would declare a variable of the desired type, except you add [] after the type. Here is a simple Java array declaration example:

int[] intArray;

int   intArray[];

 

String[] stringArray;

String   stringArray[];

 

MyClass[] myClassArray;

MyClass   myClassArray[];


Instantiating an Array in Java

When you declare a Java array variable you only declare the variable (reference) to the array itself. The declaration does not actually create an array. You create an array like this:

double[] stringArray=new double[50];

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

class ArrayExample{ 

    

           public static void main(String[] args) {

                 double[] myList = {1.9, 2.9, 3.4, 3.5};

 

                 // Print all the array elements

                 for (int i = 0; i < myList.length; i++) {

                    System.out.println(myList[i] + " ");

                 }

               

                 // Summing all elements

                 double total = 0;

                 for (int i = 0; i < myList.length; i++) {

                    total += myList[i];

                 }

                 System.out.println("Total is " + total);

                

                 // Finding the largest element

                 double max = myList[0];

                 for (int i = 1; i < myList.length; i++) {

                    if (myList[i] > max) max = myList[i];

                 }

                 System.out.println("Max is " + max); 

              }}


             

OUTPUT

1.9

2.9

3.4

3.5

Total is 11.7

Max is 3.5