Last active
December 23, 2015 02:19
-
-
Save kaydell/6565783 to your computer and use it in GitHub Desktop.
This program is a demonstration of how to correctly declare loop variables for for-loops.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This class is a demo of how to implement for-loops correctly, declaring the loop variables | |
* inside of the for-loops, to limit their scope so that the loop variables can't be used outside | |
* of the loop where the values are too big to be valid array indexes and an ArrayIndexOutOfBoundsException | |
* is thrown. | |
* | |
* @author kaydell | |
* | |
*/ | |
public class ForLoopIndexDemo { | |
/** | |
* This method demonstrates the right way to declare the loop variable called "i". | |
*/ | |
private static void runGoodLoop() { | |
int[] array = { 1, 2, 3 }; | |
for (int i = 0; i < array.length; i++) { | |
System.out.println(array[i]); | |
} | |
// i is defined inside of the for-loop, you can't use it outside of the for-loop, which is good | |
// System.out.println(array[i]); // This won't compile. array[i] would throw an exception anyways | |
} | |
/** | |
* This method demonstrates the wrong way to declare the loop variable called "i". | |
* Running this method will throw an ArrayIndexOutOfBoundsException. | |
*/ | |
private static void runBadLoop() { | |
int[] array = { 1, 2, 3 }; | |
int i; | |
for (i = 0; i < array.length; i++) { | |
System.out.println(array[i]); | |
} | |
System.err.println("An exception will be thrown next"); | |
System.out.println(array[i]); // This will compile but will throw an exception because after the loop, i is too big | |
} | |
public static void main(String[] args) { | |
runGoodLoop(); | |
runBadLoop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment