title: How to detect if an element is the last element in an array?
body: <p>The code below splits a String based on its position and then puts it into an ArrayList.</p>
  
  <p>So for example, if the String is <code>"Who Framed Roger Rabbit?"</code>, then <code>fragmentMessage</code> will split the message at every 8th character.</p>
  
  <p>So the ArrayList will look like this:  <code>[Who Fram, ed Roger,  Rabbit?]</code></p>
  
  <p>The elements of the ArrayList are as follows:</p>
  
  <ol>
  <li>ArrayList Element 0: <code>Who Fram</code></li>
  <li>ArrayList Element 1: <code>ed Roger</code></li>
  <li>ArrayList Element 2: <code>Rabbit?</code></li>
  </ol>
  
  <p>I then have a for-each loop in the main method which iterates over the ArrayList.</p>
  
  <p>How can I detect if I have reached the last element of the array when iterating?</p>
  
  <p>So for example, "<em>if this is the last element of the array, then print "LAST ELEMENT</em>".</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.List;
  
  public class LastElement {
  
  public static void main(String[] args) {
  
      String message = "Who Framed Roger Rabbit?";
      for (String fragment : fragmentMessage(message)) {
          /*
           * If "fragment" is the last element of the array, then do something
           */
      }
  }
  
  private static List&lt;String&gt; fragmentMessage(String message) {
      List&lt;String&gt; fragmentedMessage = new ArrayList&lt;&gt;();
  
      for (int i = 0; i &lt; message.length(); i = i + 8) {
          fragmentedMessage.add(message.substring(i, i + 8));
          System.out.println(fragmentedMessage);
      }
  
      return fragmentedMessage;
  }
  }
  </code></pre>