Java
Java intro
Java basics
Java variables
Java conditionals
Java loops
Java arrays
Java OOP 1
Java OOP 2
Java interfaces
Java Strings
Java user input
Java exceptions
Java packages
Java rand numbers
Java GUI's
Java GUI layout
Java events
Java applets
Java graphics
Java sounds
Java summary

Programming

Programming intro

Markup

First webpage guide HTML
XHTML

Style & Layout

CSS

Browser scripting

Javascript
VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

Java loops

Imagine you have to write a program which performs a repetitive task such as counting from 1 to 100. Coding 100 lines to do this task would be mundane. There has to be an easier way, right? This is where loops come into the picture. Loops are specifically designed to perform repetitive tasks with one set of code. Loops save alot of time.

This lesson focuses on:

The for loop

The for loop is used to repeat a task a set number of times.

Syntax:

for(int a_variable = initial_value; a_variable < end_value; 
a_variable_increment){ 
code to be executed;
}

Example:

class ForLoopExample{
	
    public static void main(String[] args){

        for(int a = 1; a < 11; a++){
	
            System.out.println(a);
          
        }
    }
}

Output:

1
2
3
4
5
6
7
8
9
10

The for loop has three parts:

Based on the above explanation of each part of the for loop, lets take a look at the loop example from earlier in the lesson and take it apart to see what each part does. Remember, that this loop prints to the screen the numbers 1 - 10.

The loop from earlier in the lesson:

class ForLoopExample{
	
    public static void main(String[] args){

        for(int a = 1; a < 11; a++){
	
            System.out.println(a);
          
        }
    }
}

The while loop

The while loop works differently than the for loop. The for loop repeats a segment of code a specific number of times, while the while loop repeats a segment of code an unknown number of times. The code within a while loop will execute while the specified condition is true.

Syntax:

while(condition is true){
execute this code;
}

Example:

class WhileLoopExample{
	
    public static void main(String[] args){

        int num = 0;

        while(num < 25){

        num = num + 5;
        System.out.println(num);	

        }
    }
}

Output:

5
10
15
20
25

In the above code, a variable named num is initialized with the value of 0. The condition in the while loop is that while num is less than 25, 5 should be added to num. Once the value of num is greater than 25, the loop will stop executing.

The do-while loop

The do-while loop is very similar to the while loop, but it does things in reverse order. The mechanism of the while loop is - while a condition is true, perform a certain action. The mechanism of the do-while loop is - perform a certain action while a condition is true. Furthermore, the code within a do-while loop will always execute at least once, even if the specified condition is false. This is because the code is executed before the condition is tested.

Syntax:

do{ 
execute this code;
}

while (condition);

Example:

class DoWhileLoopExample{
	
    public static void main(String[] args){

        int num = 0;

        do{ 
      
        num = num + 5;
        System.out.println(num);

        }

        while (num < 25);
    }
}

Output:

5
10
15
20
25

In the above code, a variable named num is initialized with the value of 5. The condition in the do-while loop is that while num is less than 25, 5 should be added to num. Once the value of num is greater than 25, the loop will stop executing.

Preventing endless loops

A necessary precaution when working with a loop is to make sure that the loop is not endless. This occurs when the condition in a loop never becomes false. To prevent endless loops, you need to ensure that the condition in a loop will eventually become false.

Example of an endless for loop:

class EndlessForLoop{
	
    public static void main(String[] args){

        for(int a = 10; a > 5; a++){
	
            System.out.println(a);
          
        }
    }
}

The above example initializes the variable a with the value of 10, and states that as long as a is greater than 5, add 1 to it. Based on the variable declaration and the increment statement, a will always be greater than 5 in this loop, and thus, it is an endless loop.

Example of an endless while loop:

class EndlessWhileLoop{
	
    public static void main(String[] args){

        int num = 50;

        while(num > 10){

        num = num + 5;

        }
    }
}

The above example initializes the variable num with the value of 50, and states that as long as num is greater than 10, add five to num. Based on the variable declaration and the increment statement, num will always be greater than 10 in this loop, and thus, it is an endless loop.

Example of an endless do-while loop:

class EndlessDoWhileLoop{
	
    public static void main(String[] args){

        int num = 50;

        do{ 
      
        num = num + 5;

        }

        while (num < 40);
    }
}

The above example initializes the variable num with the value of 50, and states that as long as num is greater than 40, add 5 to num. Based on the variable declaration and the increment statement, num will always be greater than 40 in this loop, and thus, it is an endless loop.

Breaking out of a loop

You can completely break out of a loop when it is still running. This is achieved with the break keyword. Once a loop is exited, the first statement right after it will be executed. The break keyword provides an easy way to exit a loop if an error occurs, or if you found what you were looking for.

Example:

class BreakOutOfLoop{
	
    public static void main(String[] args){

        for(int a = 1; a < 10; a++){
	
            System.out.println(a);
        
            if(a == 5){
		break;
	    }
        }

        System.out.print("You have exited the loop");
    
    }
}

In the above example, the for loop is set to iterate 9 times and print the current value of the variable a during each iteration. The if statement within the loop states that when the variable a is equal to 5, break out of the loop.

The output of this code will be:

1
2
3
4
5
You have exited the loop.

Continuing a loop

While you can break out of a loop completely with the break keyword, there is another keyword used when working with loops - the continue keyword. Using the continue keyword in a loop will stop the loop at some point and continue with the next iteration of the loop from the beginning of it.

Example:

class ContinueLoop{
	
    public static void main(String[] args){

        for(int a = 1; a < 10; a++){

              if(a == 5){
		continue;
	    }
	
            System.out.println(a);
        
        }

        System.out.print("You have exited the loop");
    
    }
}

In the above example, the for loop is set to iterate 9 times and print the current value of the variable a during each iteration. The if statement within the loop states that when the variable a is equal to 5, stop the loop and continue with the next iteration of the loop from the beginning of it. For this reason, all the numbers except the number 5 are printed.

The output of this code will be:

1
2
3
4
6
7
8
9

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments