title: A Java bounds-checking optimization example
body: <p>I have read that some of the JVMs out there can optimize code execution by removing bounds checking.  What I am trying to figure out is what coding technique will work better.</p>
  
  <p>In method <strong>example1</strong> below would the JVM ever figure it out and eliminate the bounds checking of the <strong>source[index]</strong> reference?</p>
  
  <p>Is <strong>example2</strong> the better code practice?  It would seem so, but in some algorithms inside a loop the index being out of bounds is a normal condition.  So you don't want to be generating tons of Exception objects inside that loop.</p>
  
  <pre><code>public void example1(int [] source, int index) {
      if (index &gt;= 0 &amp;&amp; index &lt; source.length)
          System.out.println("Value is " + source[index]);
      else 
          System.out.println("Out of range: " + index);
  }
  
  public void example2(int [] source, int index) {
      try {        
          System.out.println("Value is " + source[index]);        
      } catch (IndexOutOfBoundsException exp) {
          System.out.println("Out of range: " + index);
      }
  }
  </code></pre>
  
  <p>These code fragments are only representational.  I am aware that in these examples the bounds-checking will hardly matter to performance.  However I am working on an embedded protocol application where the redundant bounds checking will add up.</p>