Tuesday 6 January 2015

Java While and Do While Loops

You can use a while loop to repeat code until some condition is reached:

andrew@UBUNTU:~/Java$ cat prog68.java
public class prog68
{
public static void main (String args[])
  {
  int iteration = 1;
  while (iteration <= 5)
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog68.java
andrew@UBUNTU:~/Java$ java prog68
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Finished
andrew@UBUNTU:~/Java$


You can also use a do while loop:

andrew@UBUNTU:~/Java$ cat prog69.java
public class prog69
{
public static void main (String args[])
  {
  int iteration = 1;
  do                      
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  while (iteration <= 5);
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog69.java
andrew@UBUNTU:~/Java$ java prog69
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Finished
andrew@UBUNTU:~/Java$


The difference between the two is that the condition is evaluated before the while loop so it may not be necessary to run the code at all:

andrew@UBUNTU:~/Java$ cat prog70.java
public class prog70
{
public static void main (String args[])
  {
  int iteration = 6;
  while (iteration <= 5)
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog70.java
andrew@UBUNTU:~/Java$ java prog70
Finished
andrew@UBUNTU:~/Java$


Whereas, with the do while loop, the condition is checked at the end so the code will always be executed at least once:

andrew@UBUNTU:~/Java$ cat prog71.java
public class prog71
{
public static void main (String args[])
  {
  int iteration = 6;
  do                         
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  while (iteration <= 5);
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog71.java
andrew@UBUNTU:~/Java$ java prog71
Iteration 6
Finished
andrew@UBUNTU:~/Java$