Skip to content

For Loops

While loops are similar to for loops in functionality but differ in syntax, lets have a look at how our while loop works:

Basic while loop example

    public static void main(String[] args) {
       while (i > 0){
       System.out.println("Hello This is my message " + (i + 1));
       i--;
       }
    }

Key Differences Between For and While Loops:

Section titled “Key Differences Between For and While Loops:”
  • In situations where we know ahead of time the variables that will end a loop a for loop is preferred as it is cleaner and easier to follow.
  • while loops are better in situations where we don’t know exactly how many times we need to repeat a process. As an example awaiting a user’s input.

Example of a While Loop with User Input:

    public static void main(String[] args) {
   String input = "";
Scanner scanner = new Scanner(System.in);
       while (!input.equals("quit")){
       System.out.print("Input: ");
       input = scanner.next().toLowerCase();
       System.out.println(input)
       }
    }

Here our program can take any number of inputs and return that input back to the user, while waiting for our “quit” command. Once the quit input has been recognised our program ends the while loop and stops running.