Ads by ProfitSence
Close

How to Print an Array in Java ?

Last Updated on Wednesday 5th Oct 2022

How to Print an Array in Java

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location.

  • It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based.

  • The first element of the array is stored at the 0th index
  • The 2nd element is stored on 1st index and so on.
			
					class testArr {
  public static void main(String args[]) {
    int abc[] = new int[5]; //declaration and instantiation  
    abc[0] = 10; //initialization  
    abc[1] = 20;
    abc[2] = 30;
    abc[3] = 40;
    abc[4] = 50;
    //traversing array  
    for (int i = 0; i < abc.length; i++) //length is the property of array  
      System.out.println(abc[i]);
  }
}

			
	

Java Print Array

Output

			
					   10
   20
   30
   40
   50

			
	

Java Program to illustrate the use of declaration, instantiation and initialization of Java array in a single line

			
					  class testArr2 {
    public static void main(String args[]) {
      int abc2[] = { 11,22,33,44,55 }; //declaration, instantiation and initialization
      //printing array  
      for (int i = 0; i < abc2.length; i++) //length is the property of array  
        System.out.println(abc2[i]);
    }
  }

			
	

Output

			
					 11
 22
 33
 44
 55

			
	

For Each Loop in Java

  • We can also print the Java array using for-each loop.
  • The Java for-each loop prints the array elements one by one.
  • It holds an array element in a variable, then executes the body of the loop.
			
					class testArr3 {
  public static void main(String args[]) {
    int arr[] = { 11,22,33,44,55 };
    //printing array using for-each loop
    for (int i: arr)
      System.out.println(i);
  }
}

			
	

Output

			
					 11
 22
 33
 44
 55

			
	

Multidimensional Array in Java

  • In such case, data is stored in row and column based index (also known as matrix form).
			
					    class testArr {
      public static void main(String args[]) {
        //declaring and initializing 2D array  
        int arr[][]={{1,2,3},{4,5,6},{7,8,9}}; 
        //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();
        }
      }
    }

			
	

Output

			
					 1 2 3
 4 5 6
 7 8 9

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