Arrays can be initialized when they are declared

The array will be created large enough to hold the number of elements. And there is no need to use new.


public class Main {
  public static void main(String args[]) {

    int days[] = {31, 28, 31,};
    System.out.println("days[2] is " + days[2]);
  }
}

The output:


days[2] is 31

If you try to reference elements with negative numbers or numbers greater than the array length, you will get a run-time error.


public class Main {
  public static void main(String args[]) {

    int days[] = {31, 28, 31,};
    System.out.println("days[2] is " + days[10]);
  }
}

It generates the following error.


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
  at Main.main(Main.java:5)

The following code uses a one-dimensional array to find the average of a set of numbers.

  


public class Main {
  public static void main(String args[]) {
    double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
    double result = 0;
    int i;

    for (i = 0; i < 5; i++)
      result = result + nums[i];

    System.out.println("Average is " + result / 5);
  }
}

  

The output:


Average is 12.299999999999999
Home 
  Java Book 
    Language Basics  

Array:
  1. Introduction to Arrays
  2. Arrays can be initialized when they are declared
  3. Multidimensional Arrays
  4. Arrays length
  5. Calculate with Array