Loops in Java work similarly to how you remember loops in C/C++ most likely.
You have your counting loop (for
), as well as your pretest conditional loop (while
), and the conditional post test loop (do-while
). Each of these work the same way you would expect them to in C/C++.
For Loop
The for loop is still one of the most used loops, just like in C/C++. You have your initialization section, your condition/test section, and finally your modification section for incrementing, or decrementing, your indexing variable. The generic loop would look like:
for(<initialization>;<test condition>;<modification>) {
// loop body
}
One big difference you will find is when you loop through an array. The array object has a length property which is public, and makes it so you don’t have to have a separate variable to track array sizes like you did in C/C++; So let’s look at an example where you want to loop through an array. This will simplify your coding especially if you have to work with multiple arrays.
// assume the array "data" has been created and initialized above
for(int i = 0; i < data.length; i++) {
// print the current element to the console
System.out.println(data[i]);
}
While Loop
The while loop is the standard conditional loop what you can find in most languages, and the way is works is fairly standard as well. The general form being starting with a while
keyword, you will then have a condition in parenthesis and the while body block contained within braces.
while(<condition>) {
// while body block
}
Like all while loops, you will need to make sure you increment your index, and/or otherwise make sure you don’t get stuck in an infinite loop.
int x = 0;
while(x < 10) {
System.out.println(x); // print out x
x++; // don't forget to increment your counter
}
The good news is, if you know your conditional statements, writing a condition for a while loop, or a do-while as you’ll see next, is really easy.
Do-While Loop
The Do-While loop is very similar to the while loop. However, it is a post-test loop, meaning you do the body of the loop, then test to see if you want to run the loop again. This means you will always run the loop body at least once, which can be a huge benefit, or get you into a lot of trouble.
The layout of the do-while loop is a little different, and can be seen below.
do {
// loop body which always runs at least once
} while(<condition>); // notice the semi-colon at the end of the loop
Loops in Java was originally found on Access 2 Learn
2 Comments
Comments are closed.