What are the types of arrays in Java?


There are two types of arrays in Java they are −

Single dimensional array − A single dimensional array of Java is a normal array where, the array contains sequential elements (of same type) −

int[] myArray = {10, 20, 30, 40}

Example

Live Demo

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);
   }
}

Output

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two dimensional array is an array of one dimensional arrays and a three dimensional array is an array of two dimensional arrays.

Example

Live Demo

public class Tester {
   public static void main(String[] args) {
      int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} };
      
      for(int i = 0 ; i < 3 ; i++){
         //row
         for(int j = 0 ; j < 2; j++){
            System.out.print(multidimensionalArray[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Output

1 2
2 3
3 4

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 30-Jul-2019

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements