You are on page 1of 13

1.

Java Arrays
Arrays are objects or fundamental constructs which store multiple variables of the same type.
It can hold primitive types as well as object references. In fact most of the collection types
in Java which are the part of java.util package use arrays internally in their functioning.
Since Arrays are objects, they are created during runtime.
Or Arrays are variables used to store multiple values in a single variable, instead of declaring
separate variables for each value.

2. Features of Array
Arrays are objects
They can even hold the reference variables of other objects
They are created during runtime
They are dynamic, created on the heap
The Array length is fixed

3. Array Declaration
The declaration of array states the type of the element that the array holds followed by the
identifier and square braces which indicates the identifier is array type.
Syntax: 
int values[]; //it creates an array reference on the stack.
or
int []values;
To declare an array, define the variable type with square brackets: similarly
String[] cars; // a variable cars that holds an array of strings.

Now question is how many elements can array hold??


We have to allocate memory for the array which will define the number of elements that the
array can hold.
int []values=new int[10];
It assigns the reference of the newly created array to the variable values
Or above syntax can be written as:
int values[];
values=new int[10];
int values[]=new int[10];
so here size of the array is 10 and also called length of the array.

Note: once the length of the array is defined it cannot be changed.

- The array elements are accessed through the index that is, they start from 0
to (array_name)values.length-1.

Example1
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList where it holds ten double values and the indices
are from 0 to 9.
-if we did not store any value to an array, the array will store some default value such as 0
for int, false, etc.
-The array elements can be accessed with the help of the index. myList[0] refers to 1 , myList
[1] refers to 2 etc. we can access up to myList[n-1] where n is the size of the array. Accessing
the array with an index greater than or equal to the size of the array leads to Array
Indexoutofbounds exception
Example2: array with default value
class array
{
public static void main(String[] a)
{
int age[]=new int[5];
System.out.println(0);
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
}
Here all the elements of the array will be initialized to 0 as it’s created on the heap.

Example3:
Accessing array elements using for loop
class array
{
public static void main(String[] a)
{
int age[]=new int[5];
for(int i=0;i<5;i++) // or i<age.length
System.out.println(age[i]);
}
}

4. Initialization of an array during Declaration


Array of strings
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Similarly create an array of integers,
int[] myNum = {10, 20, 30, 40};

5. How to get the size of array?


Size of the array can be printed by arr_variable.length.To find out how many elements
an array has, we use the length property i.e array.legnth
Example4:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);

  for loop and the length property are used to specify how many times the loop should run.
The following example outputs all elements in the cars array:
Example5
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}

Example5: 
The below example initializes the array elements to 1,2,3,4,5,6 and prints them.
class array1
{
public static void main(String args[])
{
int FirstArray[] = new int[6];
for(int i=0;i<FirstArray.length;i++)
{
FirstArray[i]=i+1;
}
for(int i=0;i<FirstArray.length;i++)
{
System.out.println(FirstArray[i]);
Sytem.out.println(FirstArray.length);
}
}
}
Garbage collection and Arrays
If we declare
int aiFirstArray=null; //nullify the reference variable
Test t=new Test()
t=null;

//requesting JVM for running garbage collector


System.gc()
Or
 Runtime.getRuntime().gc();
The above statement makes the array to point to null, means the array object which was on
the heap is ready for garbage collection. Referring to array object now gives a NullPointer
Exception.
Example 6
We can also change the previous array value as given below:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo

6. Loop through an Array with for-Each


It is also called enhanced for loop, which enables us to traverse the complete array
sequentially without using an index variable.
Syntax
for (type variable : arrayname)
{
...
}

Example6
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)
{
System.out.println(i)
}
The example above can be read like this: for each  String element (called i - as in index)
in cars, print out the value of i.
If we compare the for loop and for-each loop,
for-each loop is easier to write, it does not require a counter (using the length property),
and it is more readable.

Example7
//return largest element from an array
class For_Each     
{
    public static void main(String[] arg)
    {
        {
            int[] marks = { 125, 132, 95, 116, 110 };
              
            int highest_marks = maximum(marks);
            System.out.println("The highest score is " + highest_marks);
        }
    }
    public static int maximum(int[] numbers)
    { 
        int max= numbers[0];
          
        // for each loop
        for (int num : numbers) 
        {
            if (num > max)
            {
                max= num;
            }
        }
    return max;
    }
}

7. Limitations of for-each loop

1) For-each loops are not appropriate when you want to modify the array:
for (int num : marks)
{
// only changes num, not the array element
num = num*2;
}
2) For-each loops do not keep track of index. So we can not obtain array index using for-
Each loop
for (int num : numbers)
{
if (num == target)
{
return ???; // do not know the index of num
}
}
3) For-each only iterates forward over the array in single steps
// cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]); //not possible
}
4) For-each cannot process two decision making statements at once
// cannot be easily converted to a for-each loop
for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}

8. Multidimensional Array in Java

A multidimensional array is an array containing one or more arrays.


To create a two-dimensional array, add each array within its own set of curly braces:

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java


dataType[][] arrayRefVar; (or)  
dataType arrayRefVar[][]; (or)  
dataType []arrayRefVar[];   

Example8

instantiate Multidimensional Array in Java

int[][] arr=new int[3][3]; //3 row and 3 column  

Example to initialize Multidimensional Array in Java

arr[0][0]=1;  
arr[0][1]=2;  
arr[0][2]=3;  
arr[1][0]=4;  
arr[1][1]=5;  
arr[1][2]=6;  
arr[2][0]=7;  
arr[2][1]=8;  
arr[2][2]=9;  
Example9
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
To access the elements of the myNumbers array, specify two indexes: one for the array, and
one for the element inside that array. This example accesses the third element (2) in the
second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
We can also use a for loop inside another for loop to get the elements of a two-dimensional
array (we still have to point to the two indexes):

Example8
public class MyClass
{
public static void main(String[] args)
{
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
System.out.println(myNumbers[i][j]);
}
}
}
}
9. Multidimensional Array

To declare, instantiate, initialize and print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array  
class Testarray
{  
public static void main(String args[])
{  
//declaring and initializing 2D array  
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
//printing 2D array  
for(int i=0;i<3;i++)
{  
 for(int j=0;j<3;j++)
{  
  System.out.print(arr[i][j]+" ");  
 }  
 System.out.println();  
}  
}
}  

10. Passing array to method

class sortNumbers
{
     public static void main(String[] args)
     {
           int[] data={40,50,10,30,20,5};
           System.out.println("Unsorted List is :");
           display(data);
            System.out.println("\nSorted List is :");
           display(data);
     }
     static void display(int num[])
     {
        for(int i=0; i<num.length;i++)
            System.out.print(num[i] + " ");
     }
     }
}

11. Passing matrix to the method


public class MatrixAdditionUsingFunction
{
public static void main(String[] args)
{
int[][] matrix1 = {{2, 4, 6}, {8, 2, 4}};
int[][] matrix2 = {{1, 3, 5}, {7, 9, 1}};
int[][] total = matrixAddition(matrix1, matrix2);
}
}
public static int[][] matrixAddition(int[][] x, int[][] y)
{
int arr1 = x.length;
int arr2=y.length;
total = new int[arr1][arr2];
for(int i = 0; i < arr1; i++)
{
for(int j = 0; j < arr2; j++)
{
total[i][j] = x[i][j] + y[i][j];
}
}
}
return total;
}
}

12. jagged Array in Java

Special Version of Multidimensional Array called Jagged Array. If we are creating odd
number of columns in a 2D array, it is known as a jagged array. In other words, it is an array
of arrays with different number of columns. This array is also known as “Ragged array” and
is basically an array of arrays.

It is an array of arrays where each element is, in turn, an array. A special feature of this type
of array is that it is a Multidimensional array that’s each element can have different sizes.

A two-dimensional array in Java is an array of single dimension array. In the case of a two-
dimensional array, each one-dimensional array will have different columns.

//Java Program to illustrate the jagged array  
class TestJaggedArray
{  
 public static void main(String[] args)
{       //declaring a 2D array with odd columns  
        int arr[][] = new int[3][];  
    arr[0] = new int[3];  
     arr[1] = new int[4];  
        arr[2] = new int[2];  
        //initializing a jagged array  
        int count = 0;  
        for (int i=0; i<arr.length; i++)  
            for(int j=0; j<arr[i].length; j++)  
                arr[i][j] = count++;  
           //printing the data of a jagged array   
        for (int i=0; i<arr.length; i++){  
            for (int j=0; j<arr[i].length; j++){  
                System.out.print(arr[i][j]+" ");  
            }  
            System.out.println();//new line  
        }  
    }  
}  

Above shown is a two-dimensional Jagged array. Each individual element of this array is a
one-dimensional array that has varied sizes as shown above.The first 1D array has 3 columns;
the second row has 2 columns while the third has 4 columns.

Create & Initialize Jagged Array


While creating an array of arrays you only specify the first dimension that represents a
number of rows in the array.

You can create a two-dimensional jagged array as follows:


int myarray[][] = new int[3][];

In the above declaration, a two-dimensional array is declared with three rows.

Once the array is declared, you can define it as a Jagged array as shown below:
myarray[1] = new int[2];

myarray[2] = new int[3];

myarray[3] = new int[4];


The first statement above indicates that the first row in the 2D array will have 2 columns.
The second row will have 3 columns while the third row will have 4 columns thereby
making it a jagged array.

Once the array is created, we can initialize it with values. Note that if we don’t explicitly
initialize this array (as in the above case), then it will take the default values as initial values
depending on the data type of the array.

Alternatively, we can also initialize an array as follows:


int myarray[][] = new int[][]{
  new int[] { 1, 2, 3 };
    new int[] { 4, 5, 6, 7 };
    new int[] { 8, 9 };
};
Yet another way of initializing a jagged array is by omitting the first new operator as
shown below:
int[][]myarray ={
    new int[] { 1, 2, 3 };
    new int[] { 4, 5, 6, 7 };
    new int[] { 8, 9 };
};
As you can see above, the new operator is omitted and the array is initialized as well as
declared in the same statement.

We can also omit all the new operators altogether and have a declaration and
initialization statement as shown below.
int[][] arr = {
    { 1, 2, 3 },
    { 4, 5, 6, 7 },
    { 8, 9 } };
The program below initializes a ragged array by assigning initial values to each row.
Here each row of the array is initialized to the column values.

Example 10
class Main
{
    public static void main(String[] args)
    {
        // Declare a 2-D array with 3 rows
       int myarray[][] = new int[3][];
 
       // define and initialize jagged array
 
       myarray[0] = new int[]{1,2,3};
       myarray[1] = new int[]{4,5};
       myarray[2] = new int[]{6,7,8,9,10};
 
       // display the jagged array
       System.out.println("Two dimensional Jagged Array:");
       for (int i=0; i<myarray.length; i++)
       {
          for (int j=0; j<myarray[i].length; j++)
              System.out.print(myarray[i][j] + " ");
          System.out.println();
        }
    }
}

As shown in the output, the first row of Jagged array has 3 columns, the second row has 2
columns and the third row has 5 columns.

Example11
Given below is an example of a Jagged array in Java. Here the array is initialized using for
loops.
class Main
{
     public static void main(String[] args)    {
        // Declaring 2-D array with 4 rows
       int intArray[][] = new int[4][];
       // create a jagged array
       intArray[0] = new int[3];
       intArray[1] = new int[2];
       intArray[2] = new int[1];
       intArray[3] = new int[4];
 
       // Initializing array with values
       for (int i=0; i<intArray.length; i++)
          for(int j=0; j<intArray[i].length; j++)
             intArray[i][j] = (i+1) * (j+1);         //initial values for each row,column
 
        // display the contents of 2-D jagged array
       System.out.println("Two-dimensional Jagged Array:");
       for (int i=0; i<intArray.length; i++)
       {
           for (int j=0; j<intArray[i].length; j++)
               System.out.print(intArray[i][j] + " ");
           System.out.println();
        }
    }
}
The above program defines a Jagged array of 4 rows. The column numbers of each row are
then defined thereby creating an array of arrays. Then using for loops that traverse both rows
and columns, the initial values are assigned to this array. The array is then printed using for
loops.

Let's implement another example of Ragged/Jagged arrays. In this program, we create a


Jagged array in such a way that the ith row has i number of columns. This means that for row
#1 the number of column(s) will be 1, row #2 will have 2 columns, row #3 will have 3
columns and so on.

Example12

class Main
{
    public static void main(String[] args)  
{
        // Declare a 2-D array with 5 rows
        int intArray[][] = new int[5][];
          // create a jagged array that has i column(s) for ith row
         for (int i=0; i<intArray.length; i++)
           intArray[i] = new int[i+1];
          // Initialize the jagged array
         int count = 0;
         for (int i=0; i<intArray.length; i++)
            for(int j=0; j<intArray[i].length; j++)
               intArray[i][j] = count++;
 
        // Display the values of 2D Jagged array
       System.out.println("A two-dimensional Jagged Array contents:");
       for (int i=0; i<intArray.length; i++)
        {
           for (int j=0; j<intArray[i].length; j++)
               System.out.print(intArray[i][j] + " ");
           System.out.println();
        }
    }
}

The above program output shows that each row has the number of columns equal to the
corresponding row number. The elements are initialized to a sequence starting from 0.

You might also like