Array in Java

 Array in Java

Java array is an object which contains elements of a similar data type. In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java.

Java provides the feature of anonymous arrays which is not available in C/C++.

Java array

Advantages

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.

Disadvantages

  • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax

DataType[] arrayReferenceVar;  //preferred way to declare array.
       OR
DataType []arrayReferenceVar;  //preferred way to declare array.
       OR
DataType arrayReferenceVar[];  //works but not preferred way.

Note − The style DataType [] arrayRefVar is preferred. The style DataType arrayReferenceVar[] comes from the C/C++ language and was adopted in Java.

Creating Arrays

You can create an array by using the new operator with the following syntax −

Syntax

arrayReferenceVar = new DataType[arraySize];

The above statement does two things −

·        It creates an array using new DataType [arraySize].

·        It assigns the reference of the newly created array to the variable arrayReferenceVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −

DataType[] arrayRefenceVar = new DataType[arraySize];

The code snippets of this above 2 syntax

int []arr=new int[2];

arr[0]=10;

arr[1]=15; 

System.out.println(arr[0]);

System.out.println(arr[1]);

 

Alternative way to create arrays as follows

DataType[] arrayRefenceVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example

String[] name={"Deepak","Rahul","Sagar","Pravat","Papu"};
 
//printing elements of array
for(int i=0;i<name.length;i++){
 
     System.out.println(name[i]);
 
}              
               
System.out.println("====="+name
[2]);

 

Example

Assign 1 to 10 numbers in an array and print all elements using for loop

package com.test;
 
public class ArrayExample2 {
       public static void main(String[] args) {
 
              //with the help of Array
              int []arr=new int[10];
             
              //assign value to array elements
              for(int i=0;i<10;i++){
                    
                     int number=i+1;
                     arr[i] = number;    
                    
              }
             
              System.out.println("Size of array :"+arr.length);
             
              //printing elements of array
              for(int i=0;i<10;i++){
                    
                     System.out.println(arr[i]);
                    
              }
       }
}

Output


Size of array :10
1
2
3
4
5
6
7
8
9
10


The foreach Loops

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example

The following code displays all the elements in the array myName 


public class TestArray2 {

    public static void main(String[] args) {

      String [] myName = {"Rahul", "Papu", "Deepak", "Prabhat"};

       // Print all the array elements

      for (String name: myName) {

         System.out.println(name);

      }

   }

}

This will produce the following result −

Output

Rahul
Papu
Deepak
Prabhat

 

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

  1. DataType[] arr; (or)  
  2. DataType[]arr; (or)  
  3. DataTypearr[];  

Multidimensional Array in Java

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

Syntax to Declare Multidimensional Array in Java


  1. dataType[][] arrayRefVar; (or)  
  2. dataType [][]arrayRefVar; (or)  
  3. dataType arrayRefVar[][]; (or)  
  4. dataType []arrayRefVar[];   

Example to instantiate Multidimensional Array in Java

    package com.test;
     
    public class ArrayExample5 {
     
           public static void main(String[] args) {
     
     
                  String[][] name= new String[2][2];
     
                  name[0][0]="Rahul";
                  name[0][1]="Papu";
                  name[1][0]="Sagar";
                  name[1][1]="Prabhat";
     
                  System.out.println(name[0][1]);
                  System.out.println(name[1][0]);
           }
    }


    Output

    Papu
    Sagar

    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.

    Example

    Here is a complete example showing how to create, initialize, and process arrays −

    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. Here, myList holds ten double values and the indices are from 0 to 9.





    public class TestArray {
     
       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); 
       }
    }

    This will produce the following result −

    Output

    1.9
    2.9
    3.4
    3.5
    Total is 11.7
    Max is 3.5



    Copying a Java Array

    We can copy an array to another by the arraycopy() method of System class.

    Syntax of arraycopy method

    1. public static void arraycopy(  
    2. Object src, int srcPos,Object dest, int destPos, int length  
    3. )  

    Example of Copying an Array in Java

    1. //Java Program to copy a source array into a destination array in Java  
    2. class TestArrayCopy{  
    3.     public static void main(String[] args) {  
    4.         //declaring a source array  
    5.         char[] copyFrom = { 'a''b''c''d''e''f''g',  
    6.                 'h''i''j''k''l''m' };  
    7.         //declaring a destination array  
    8.         char[] copyTo = new char[7];  
    9.         //copying array using System.arraycopy() method  
    10.         System.arraycopy(copyFrom, 2, copyTo, 07);  
    11.         //printing the destination array  
    12.         System.out.println(String.valueOf(copyTo));  
    13.     }  
    14. }  

    Output:

    caffein
    

    Cloning an Array in Java

    Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java array which means it copies the references.

    1. //Java Program to clone the array  
    2. class Testarray1{  
    3. public static void main(String args[]){  
    4. int arr[]={33,3,4,5};  
    5. System.out.println("Printing original array:");  
    6. for(int i:arr)  
    7. System.out.println(i);  
    8.   
    9. System.out.println("Printing clone of the array:");  
    10. int carr[]=arr.clone();  
    11. for(int i:carr)  
    12. System.out.println(i);  
    13.   
    14. System.out.println("Are both equal?");  
    15. System.out.println(arr==carr);  
    16.   
    17. }}  

    Output:

    Printing original array:
    33
    3
    4
    5
    Printing clone of the array:
    33
    3
    4
    5
    Are both equal?
    false
    

    Addition of 2 Matrices in Java

    Let's see a simple example that adds two matrices.

    1. //Java Program to demonstrate the addition of two matrices in Java  
    2. class Testarray5{  
    3. public static void main(String args[]){  
    4. //creating two matrices  
    5. int a[][]={{1,3,4},{3,4,5}};  
    6. int b[][]={{1,3,4},{3,4,5}};  
    7.   
    8. //creating another matrix to store the sum of two matrices  
    9. int c[][]=new int[2][3];  
    10.   
    11. //adding and printing addition of 2 matrices  
    12. for(int i=0;i<2;i++){  
    13. for(int j=0;j<3;j++){  
    14. c[i][j]=a[i][j]+b[i][j];  
    15. System.out.print(c[i][j]+" ");  
    16. }  
    17. System.out.println();//new line  
    18. }  
    19.   
    20. }}  

    Output:

    2 6 8
    6 8 10
    

    Multiplication of 2 Matrices in Java

    In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the second matrix which can be understood by the image given below.

    Matrix Multiplication in Java

    Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

    1. //Java Program to multiply two matrices  
    2. public class MatrixMultiplicationExample{  
    3. public static void main(String args[]){  
    4. //creating two matrices    
    5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
    6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
    7.     
    8. //creating another matrix to store the multiplication of two matrices    
    9. int c[][]=new int[3][3];  //3 rows and 3 columns  
    10.     
    11. //multiplying and printing multiplication of 2 matrices    
    12. for(int i=0;i<3;i++){    
    13. for(int j=0;j<3;j++){    
    14. c[i][j]=0;      
    15. for(int k=0;k<3;k++)      
    16. {      
    17. c[i][j]+=a[i][k]*b[k][j];      
    18. }//end of k loop  
    19. System.out.print(c[i][j]+" ");  //printing matrix element  
    20. }//end of j loop  
    21. System.out.println();//new line    
    22. }    
    23. }}  

    Output:

    6 6 6 
    12 12 12 
    18 18 18 
    


    ArrayIndexOutOfBoundsException

    The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in negative, equal to the array size or greater than the array size while traversing the array.

    //Java Program to demonstrate the case of   
    //ArrayIndexOutOfBoundsException in a Java Array.  
    public class TestArrayException{  
        public static void main(String args[]){  
            int arr[]={10,20,20,40};  
            for(int i=0;i<=arr.length;i++){  
            System.out.println(arr[i]);  
           }  
        }
    }

    Output:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    	at TestArrayException.main(TestArrayException.java:5)
    10
    20
    30
    40
    




































    Comments

    Popular Topics

    What is JSP. How to create one JSP application in Eclipse

    Data Types in PL/SQL

    How to develop a RESTful webservice in java ?

    Features of Java

    What is JDBC ?

    If you have any query or suggestions, Please feel free to write us

    Name

    Email *

    Message *