Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Links | Search | Bio |

Guide to Object-oriented Programming With Java (Buffalo State University Version)


Chapter 9: Using Loops

Java provides a few different control structures that allow you to loop through data using a set of statements.

The Java for Loop

The for statement provides a way to loop through a statement, or group of statements, a number of times.

for (int i = 0; i < 5; i++) {
  int doubled = i * 2;
  System.out.print(i + " * 2 = " + doubled);
}

Figure 9-1: A Java for Loop
Console
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 9
5 * 2 = 10

Figure 9-2: Java for Loop Output

The Java for Loop With an Array

The for loop statement also provides a way to "walk" through an array.

int[] numbers = { 1,2,3 };
for (int item:= numbers) {
  System.out.print("Count is: " + item);
}

Figure 9-3: Java for Array Loop
Console
Count is: 1
Count is: 2
Count is: 3

Figure 9-4: Java for Array Loop Outuput

The Java while Loop

The while loop statement provides a way to to perform a statement or statements based on a condition being true or false.

int i = 5;
while (i < 5; i++) {
  int doubled = i * 2;
  System.out.print(i + " * 2 = " + doubled);
}

Figure 9-5: Java while Loop
Console
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 9
5 * 2 = 10

Figure 9-6: Java while Loop Outuput

The Java do / while Loop

The do ... while loop statements provide a way to to perform a statement or statements based on a condition being true or false. A do ... while loop tests the condition at the end of the loop. S, a do ... while loop will always execute at least once.

int i = 5;
do {
  int doubled = i * 2;
  System.out.print(i + " * 2 = " + doubled);
  i++;
} while (i < 5);

Figure 9-7: Java do / while Loop
Console
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 9
5 * 2 = 10

Figure 9-8: Java do ... while Loop Outuput

Let's get started with a While program!

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2024 Jim Gerland