Site Search:

Create and use do/while loops

Back OCAJP


We have seen while loop in a previous post, in this post, we will cover do/while loop with examples.

The only difference between while loop and do/while loop is that do/while loop guarantees to be run at least once.


OCAJP>cat test.java 
class test{
  public static void main(String...args) {
    int m = 0, n = 4;
    while(m < n) {
      m++;
      n--;
      System.out.println(m+","+n);
    }
    System.out.println(n=(m=0)+4);
    do{
      m++;
      n--;
      System.out.println(m+","+n);
    }while(m < n); 

    System.out.println('A' + "A" + new Character('A').toString() + (int)'A');    
    while(m < n) {
      m++;
      n--;
      System.out.println(m+","+n);
    }
    do{
      m++;
      n--;
      System.out.println(m+",,"+n);
    }while(m < n); 
  }
}
OCAJP>javac test.java 
OCAJP>java test
1,3
2,2
4
1,3
2,2
AAA65
3,,1
Back OCAJP