Java – array basics

Initialize arrat and print length

public class Main {
  public static void main(String[] args) {
    int[] arr = {10, 21, 3};
    System.out.println(arr.length);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   1538
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Access element at specific index

public class Main2 {
  public static void main(String[] args) {
    int[] arr = {10, 21, 3};
    // Print element at index 1
    // index starts from 0
    System.out.println(arr[1]);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   1550
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Access non existing index

This will throw Index Out Of Bounds Exception

public class Main3 {
  public static void main(String[] args) {
    int[] arr = {10, 21, 3};
    // index out of bound
    System.out.println(arr[10]);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   1562
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments