Array Bounds Checks - Java Language Basics

Java examples for Language Basics:Array

Description

Array Bounds Checks

Demo Code

public class Main {
  public static void main(String[] args) {
    int[] test = new int[3];
      /*from  ww  w  .  j a v a 2  s.  co  m*/
    System.out.println("Assigning 12 to the first element");
    test[0] = 12;  // index 0 is between 0 and 2. Ok

    System.out.println("Assigning 9 to the fourth element");
    
    // index 3 is not between 0 and 2. At runtime, an exception is thrown.
    test[3] = 9; 
    
    System.out.println("We will not get here");    
  }
}

Related Tutorials