Looping in Java

Alright, hold on to your bits and bytes, because we’re about to go on a wild ride through the looping possibilities in Java!

The Loops

For – Loop

First up, we have the classic “for” loop. This is the loop you know and love from your early days of coding. It allows you to iterate through a range of values, incrementing or decrementing a variable with each iteration. For example, you could use a for loop to print out the numbers from 1 to 10:

for (int i = 1; i <= 10; i++) {
  System.out.println(i);
}
Java

While – Loop

Next up, we have the “while” loop. This loop continues to execute as long as a certain condition is true. This can be useful when you don’t know ahead of time how many times you need to loop. For example, you could use a while loop to repeatedly prompt a user for input until they enter a valid value:

Scanner input = new Scanner(System.in);
int value = 0;

while (value <= 0) {
  System.out.println("Enter a positive integer:");
  value = input.nextInt();
}
Java

Do – While 

If you’re feeling particularly adventurous, you could try out the “do-while” loop. This loop is similar to the “while” loop, but it always executes at least once, even if the condition is false to begin with. For example, you could use a do-while loop to repeatedly ask a user if they want to play a game until they finally say yes:

Scanner input = new Scanner(System.in);
String answer;

do {
  System.out.println("Do you want to play a game? (yes/no)");
  answer = input.nextLine();
} while (!answer.equals("yes"));
Java

ForEach – Loop

Finally, we have the “for-each” loop. This loop is a convenient way to iterate through the elements of an array or collection without having to worry about the index. For example, you could use a for-each loop to print out the elements of an array:

int[] numbers = {1, 2, 3, 4, 5};

for (int number : numbers) {
  System.out.println(number);
}
Java

Tips and Tricks for Looping in Java

If possible, use ‘break’.

‘Break’ is a keyword in Java that allows you to exit a loop prematurely. This can be particularly useful when you’re searching for a specific item in a loop and want to exit the loop as soon as you find it. By using ‘break’, you can save yourself from unnecessary iterations and improve the efficiency of your code.

// set up a counter and a boolean variable
int count = 0;
boolean found = false;

// loop until we find the number we're looking for or exceed a certain count
while (count < 10 && !found) {
  // generate a random number
  int num = (int)(Math.random() * 100);
  
  // check if the number is divisible by 5
  if (num % 5 == 0) {
    // print the number and set found to true
    System.out.println("Found a number divisible by 5: " + num);
    found = true;
    // exit the loop
    break;
  }
  count++;
}

// print a message if we didn't find the number
if (!found) {
  System.out.println("Couldn't find a number divisible by 5 within " + count + " tries.");
}
Java

Count backwards.

To count backwards, you can utilize a for loop in Java. With a for loop, you can specify the starting point of the loop as well as how the loop variable should change with each iteration. By setting the loop variable to a higher value at the start and decrementing it with each iteration, you can effectively count backwards. This approach provides you with the flexibility to define the initial value and iteration steps based on your specific needs.

// loop through numbers from 10 to 1
for (int i = 10; i >= 1; i--) {
  System.out.println(i);
}
Java

Deterministic is the way.

It’s important to prevent infinite loops in your code as they can cause your program to hang or crash. To avoid infinite loops, you should ensure that the condition for the loop to continue is based on a reliable and predictable factor, rather than a random one. By doing so, you can increase the stability and reliability of your code, and avoid potential errors or crashes that may result from infinite loops.

// loop until we roll a 6 on a dice
int roll = 0;
while (roll != 6) {
  // simulate rolling a dice
  roll = (int) (Math.random() * 6) + 1;
}
Java

Use Continue.

To skip a part of the loop iteration, you can use the ‘continue’ keyword in Java. When ‘continue’ is encountered within a loop, it causes the loop to immediately jump to the start of the next iteration and skip any remaining code within the current iteration. This can be useful when you need to skip over certain iterations of a loop based on a specific condition, allowing you to avoid executing unnecessary code and improve the efficiency of your program.

for (int i = 1; i <= 10; i++) {
  // if i is divisible by 3, skip this iteration
  if (i % 3 == 0) {
    continue;
  }
  System.out.println(i);
}
Java

The forbidden ONE

Looping in Java is quite simple, so let’s get a bit oldshool with goto. Technically speaking, you could use goto to construct a loop in Java, but it’s a bit like using a fork to eat soup. Java provides a variety of other loop structures, like for, while, and do-while loops, which are designed to be more structured and less likely to end up with soup on your shirt.

But if you’re feeling adventurous and want to give it a try, here’s an example of how you could use goto to construct a simple loop in Java:

// initialize a variable
int i = 0;

// create a label for the loop
loop: 

// use the goto statement to jump to the label
i++;
if (i < 10) {
  System.out.println(i);
  goto loop;
}
Java

In this example, we’re using the goto statement to create a loop that increments the value of i and prints it to the console until the value of i is equal to 10. It’s a bit like playing a game of hopscotch, but instead of squares on the ground, we’re jumping around the code.

Of course, as I mentioned earlier, it’s generally not recommended to use goto for loop control in Java, as it can make the code harder to read and maintain. But if you’re feeling bold and want to give it a try, just remember to bring your soup spoon!

Leave a Reply