قالب وردپرس درنا توس
Home / Tips and Tricks / Using loops in Java

Using loops in Java



Loops in Java

A loop is a structure in programming that allows you to run the same section of code over and over. This can be used when you want to perform an iterative task (such as counting or sorting a list) or when you want to create a continuous, cyclical experience for the user (like in a game loop). In this post, we’ll explore how loops are used in Java.

Also read: Using loops in Python

For loops in Java

There are three types of loops in Java:

  • For loops
  • While loops
  • Do-while loops

Starting with for loops, this is the best option for iterative tasks. The reason is that for loops have a fixed number of iterations. We write this out by first initializing a variable, then setting the condition, and finally defining the increments.

For example:

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

Here we use the integer "n". The loop is executed as long as n is less than or equal to 1. The value of n increases by one with each iteration.

Run this code and it will simply count from 1-10 on the screen.

When we said:

for (int n=1;n<=20;n+=2) {
    System.out.println(n);
    }

We'd see the numbers 1-19 that count in pairs! And so on.

And we don't necessarily have to use whole numbers:

   for (String hi = "hi";hi.length()<=10;hi = hi + "h") {
    System.out.println(hi);
    }

While loops in Java

While loops work the same as they do for loops, except that you can determine each condition using values ​​you may have defined elsewhere in your code. To use while loops in Java, all you need to do is add the condition in parentheses.

  int health=10;

  while(health > 0) {
    System.out.println(health);
    health--;
  }
}

Do while loops

A do while loop is very similar to a while loop, except that the structure is turned upside down so that the block of code is always executed at least once.

do{
    System.out.println(health);
  } while(health > 0);

Here you will see "Health = 0" when health is lower than one.

Which loop should be used when?

If all of these different loops are misleading you, it may be helpful to understand why we have three approaches to doing essentially the same thing.

  • For loops are useful when you have a fixed number of iterations. For example, this is a great way to step through a text document line by line. (First you would need to find the number of rows.)
  • While loops are useful when you need something that should run indefinitely until a certain condition is met. A good example could be your game loop, which can run until the player clicks Exit or runs out of health. Our post shows you how to write your first Android game in Java to demonstrate how this could work.
  • Finally, do while loops can be used when you want to execute a block of code at least once. For example, in many user interface scenarios it can be helpful to let the user know when there is nothing to do.

Of course, there are workarounds for doing all of these things using any of the various loops in Java! However, choosing the right code for the job is the hallmark of efficient programming.

Java break and continue statements

Before you can claim to have mastered loops in Java, you must grapple with the "break" statement. A break statement is your "get-out clause" with which you can effectively break the loop at any time.

For example, you might want to loop your game until the user dies, but you also want to allow them to exit at any time. You can use the break statement to do this:

  int specialCondition = 3;
  int health=10;

  while(health > 0) {
    System.out.println(health);
    health--;

    if (specialCondition == 3) {
      System.out.println("Special condition met!");
      break;
    }

  }

The "continue" statement works in a similar way, but allows you to return to the beginning of the loop and cut off everything below. This can be useful to avoid complex, nested if statements in your loop.

There are other fancy tricks we can do such as: B. nesting loops and using labels. These are topics that we may come back to in the future. Right now, you know all of the essential skills you need to start looping!

Also read: How to print an array in Java

Want more? Then check out our free, comprehensive beginner's Java course for a thorough understanding of the language. Alternatively, check out numerous full courses on our list of the best resources for learning Java.


Source link