Program Flow  «Prev 

Infinite while loops


Generally speaking, infinite loops are a bad thing because there is usually no way for a program to exit out of one. Following is a simple example of an infinite while loop:
while (true)
  System.out.println("Keeps on going...");

Loop condition

Since the loop condition in this example is permanently set to true, the loop never exits and will repeat infinitely. Of course, you can manually terminate the program, which will ultimately end the loop.
Before you start thinking that infinite loops are always to be avoided, let me say that there are some occasions where an infinite loop is useful. For example, some multithreaded programs use infinite while loops to carry out a task as long as the thread is active. In this case, the program can kill the threaded task whenever it needs to so the infinite loop really does not continue on forever.
You will learn about multithreaded Java programming later in the series.

What can you do to make the following code compile?
public class TestClass
{
	public static void main(String[] args) {
	  int[] values = { 10, 20, 30 }; 
	  for( /* put code here */ ){ //
	  }
	}// end - main
}
Select 2 options
  1. int k : values
  2. int k in values
  3. int k in values
  4. ;;
  5. ; k< values.length; k++


Answer: a, d
Explanation:
c. k must be initialized first. So it should be:
int k=0; k<0; k++ 

d. It will cause an infinite loop, but it is valid.
e. k needs to be declared first.