Website For Developers

Array in Java



Syntax

dataType[] array; // preferred way.
or
dataType array[]; // It also work fine.

// preferred way.
int [] myList;
// another way
int myList [];


Declare an array in Java

There are a different ways of declaration of an array in Java.

1-

   int[] array = {1,2,3};
   String[] array = {"a","b","c"};

2-

   int[] array = new int[3];
   String[] array = new String[3];

3-

   int[] array = new int[]{1,2,3};
   String[] array = new String[]{"a","b","c"};


Example of array in Java

public class ArrayDouble {

   public static void main(String[] args) {
    double[] array = {1.1, 2.2, 3.3, 4.4, 5.5};
    // Printing array elements
    for (int i=0; i<array.length; i++) {
      System.out.println(array[i] + " ");
    }
  }
}

Output

1.1
2.2
3.3
4.4
5.5


Array example with for-each loop

public class ForeachArray {

  public static void main(String[] args) {
    String[] array = {"Orange", "Blue", "Purple", "Black"};
    // Printing array elements
    for (String color: array) {
      System.out.println(color);
    }
  }
}
Output

Orange
Blue
Purple
Black



Arrays in Methods / Array as a method Parameter

Arrays in methods Example

public class SumOfArray {

  public static void main(String[] args) {
    int[] array = {5,4,5,6,5};
    sum(array); //passing array to method
  }
  static void sum(int array[]) {
    int total = 0;
    for(int i=0; i<array.length; i++) {
      total += array[i];
    }
  System.out.println(total);
}
}
Output

25