Sunday, 13 October 2019

Java Tutorials | Pitfalls of Loops


While using the loops, we should keep in mind for the initialization, termination and update condition. Otherwise, there will be unexpected behavior of the program.

Infinite loop
One of the most common mistakes while implementing any sort of looping is that that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.

Java program to illustrate infinite loop:
/**
 * In this loop condition is not terminated properly which leads to infinite
 * loop.
 *
 * @author rajesh.dixit
 */
public class LoopPitfallTest {

     public static void main(String[] args) {

          // infinite loop because termination condition is not properly used.
          // condition should have been i>0.
          for (int i = 5; i > 0; i++) {
               System.out.println(i);
          }

          int x = 5;
          // infinite loop because update statement is not provided.
          while (x == 5) {
               System.out.println("In the loop");
          }
     }
}

OutOfMemory Error
Another pitfall is that you might be adding something into collection object through loop and program can run out of memory. Please try and execute the below program, after some time, out of memory error will be thrown.

Java program for out of memory exception:
import java.util.ArrayList;

/**
 * In this loop condition is not terminated properly which leads to infinite
 * loop.
 *
 * @author rajesh.dixit
 */
public class LoopPitfallTest {

     public static void main(String[] args) {
          ArrayList ar = new ArrayList<>();
          for (int i = 0; i < Integer.MAX_VALUE; i++) {
               ar.add(i);
          }
     }
}
Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     at java.util.Arrays.copyOf(Arrays.java:3210)
     at java.util.Arrays.copyOf(Arrays.java:3181)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...