Using Loops

Using loops can be one of the most useful operations in any language. Depending on the type of loop that you will be using  you can loop through a set of numbers, continue the loop while a value is true or false, or do something before the loop starts.

We are going to take a look at some commonly used loops within Java. Commonly used loops are; for, while, and do while.

First let’s take a look a the for loop:

//Create a new method, just for fun!
public void forLoop(){
     //Now let's begin the loop
     for(int i = 0; i < 10; i++){ //initializes i as an Integer and sets it to 0.
          //if i is less than 10 it will print "Your number is 1"
          //once the loop starts it will add 1 to i
          System.out.println(&quot;Your number is &quot; + i);
     }
}

public void whileLoop(){
     int i = 0; //initializes i as an Integer and sets it to 0.
     while(i < 10){ //starts loop while i is less than 10
          System.out.println("Your number is " + i); //continues to print "Your number is 1";
          i++; //add 1 to i and continues loop
     }
}

public void doWhileLoop(){
     int i = 0; //initializes i as an Integer and sets it to 0.
     do{
     //Does this first before anything. It will always do it once
          System.out.println("Your number is " + i); //continues to print "Your number is 1";
     }while(i < 10); //continues the loop until it reaches 10
}
About bwilson 37 Articles
Mobile device specialist currently working as a system analyst, building out an IT infrastructure. I currently focus much of my work on relational databases as well as frameworks. The goal of my work is to continually improve processes and efficiencies.

Be the first to comment

Leave a Reply

Your email address will not be published.


*