Skip to main content

Loops in Java

 Loops in Java is one of the important concepts. When we have to execute some task again and again, we can do that same either by repeating the same block of codes multiple times.

Or a better solution is creating a loop in Java. In this case loop can be very helpful, because loop will reduce the execution time and make the program very tiny.




We can specify how many times we have to run the same code through loops in Java programming and the same thing will happen seamlessly.

The expression will be in the form of a condition which will be evaluated every time before the execution of a specific statement. As long as the expression returns a true value, the program will execute the statement or the specified task.

When a loop is being used in Java programming, the program’s readability gets increased which lets the other programmers to understand the code very easily and eventually it reduces any possible error in programming.

 

How many loops in Java Programming:

There are three loops used in Java programming.

  • While Loop
  • Do While Loop
  • For Loop

These are conditional programming having different syntax. The loops will allow execution of certain codes upon validation of specified conditions.

 

While Loop in Java:

‘While loop’ in Java is a conditional programming where the execution of certain program or ‘code block’ depends upon the validation of an expression. As long as the expression returns the true value, it will loop through the ‘code block’.

 

The syntax of While Loop in Java:

 

while (condition) {

       //Codes executed upon validation of given condition.

        }

 

 

If you see the syntax of Java while loop, you will notice there is a condition mentioned inside the parentheses and only upon fulfilling of such condition, the code-block inside the curly braces will be executed.

The value of the variable initiated inside the condition must be incremented with every iteration of the code block between the curly braces. Otherwise it will become an infinite loop.

Programming example of Java While Loop:

 

package java_loops;

import java.util.Scanner;

 

public class while_loop {

 

    public static void main(String[] args) {

        

         Scanner sc = new Scanner(System.in);

        

         String name;

         System.out.println("Enter your name:");

         name = sc.nextLine();

        

         int x;

         System.out.println("How many times do you Want to print your name?");

         x = sc.nextInt();

        

         int count=0;

         while (count<x) {

              System.out.println(name);

              count++;

         }

        

    }

 

}

 

 

 

 

Output in the Console:

 

Enter your name:

Michael

How many times do you Want to print your name?

5

Michael

Michael

Michael

Michael

Michael

 

 

Do While Loop in Java:

‘Do While loop’ in Java is a conditional programming where the execution of certain program or ‘code block’ depends upon the validation of an expression.

‘Do While loop’ in Java is quite similar as compared to ‘while loop’, the only difference in ‘Do while loop’ is, it allows the code blocks inside the curly braces to be executed at-least once before evaluating the condition and thereafter the condition is checked.

If the condition evaluates to be true, the program continues to loop through the statement until and unless the condition remains true.

 

The syntax of Do While Loop in Java:

 

     do {

     //Codes executed upon validation of given condition.

     }

   while (condition);

 

 

If you see the syntax of Java do while loop, you will notice unlike ‘while loop’ the condition of ‘Java do while loop’ is mentioned after the code blocks.

Which means the code blocks will be executed at-least once before evaluation of the condition and if the condition does not return a true value, the program will not execute further.

In ‘do while loop‘ also, the value of the variable initiated inside the condition must be incremented with every iteration of the code block between the curly braces. Otherwise it will become an infinite loop.

 

Programming example of Java Do While Loop (Example 1):

 

package java_loops;

 

public class do_while_loop {

 

     public static void main(String[] args) {

         

         

          int count=0;

          do  {

 

                   System.out.println(count);

                   count++;

              }

          while (count<10);

 

     }

 

}

 

 

 

 

Output in the Console:

 

  0

  1

  2

  3

  4

  5

  6

  7

  8

  9

 

 

Programming example of Java Do While Loop (Example 2):

 

  package java_loops;

 

public class do_while_loop {

 

   public static void main(String[] args) {

       

       

        int count=10;

        do  {

 

                  System.out.println(count);

                  count++;

             }

        while (count<10);

 

     }

  }  

 

 

 

Output in the Console:

 

  10

 

 

 

As you can see in the programming example of ‘Java Do While Loop’, the statement is executed at-least once even if the condition evaluates to be false.

This is the only exception in ‘Java do while loop’ if we compare the same with ‘Java while loop’.

 

For Loop in Java:

Syntax wise ‘java for loop’ is much simpler and easy to remember as compared to other two loops.

Unlike ‘java while loop’, ‘java for loop’ syntax is so designed that it incorporates variable declaration, initialization, condition validation and variable increment all under one syntax.

Hence this loop is quite easy to write and remember by the developers.

It is also said that, this loop is used when a developer is aware exactly how many times he or she will loop through a statement.

That means when it is know how many times the execution of a statement will be happened, for loop is used.

 

  The syntax of For Loop in Java:

 

          for (variable declaration & initialization; condition validation; variable value increment/decrement) {

              // Code block to be executed;

          }

 

 

If you see the syntax of ‘for while loop’, you will notice unlike ‘while loop’ the variable declaration, initialization, condition validation and value of variable change all happens inside the parenthesis.

After that the executable code block has been written inside curly braces.

 

Programming example of Java For Loop:

 

  package java_loops;

 

  public class for_loop {

 

      public static void main(String[] args) {

 

            for (int i=7;i<10;i++) {

                System.out.println(i);

            }

 

       }

 

  }

 

 

 

Output in the Console:

 

  7

  8

  9

 

 

Sum Up:

After going through the above lesson on ‘loops in Java’, you should be able to clearly understand the syntax of different loops and their best uses.


Comments

Popular posts from this blog

What is Java

Java is a general purpose programming language. Which means this programming language is used in many purposes apart from being used only in android application development. There are a few similarities between Java programming language and C++ programming language. But Java programming language is having some advanced features which you are going to learn in future. In programming languages you write programs in the form of statements in many lines and those statements are executed one by one. In Java, the execution happens really fast and concurrently it can execute many statements. Java is a platform independent (Java compiled byte code can be run across different operating systems) and object oriented programming language.   Why should we learn Java programming language?   Easy to learn: Java is a easy to learn programming language. Once you start learning Java programming, you will actually be learning the real programming and you will observe everyth...

Java User Input Exercise

Exercise 1: Write a simple java program to take user input of a number and store it inside an integer variable. Later print the number on the screen.   Solution 1:   import java.util.Scanner;   public class UserInpur {        public static void main(String[] args ) {               Scanner sc = new Scanner(System. in );           System. out .println( "Enter a number" );           int x = sc .nextInt();           System. out .println( "You have entered:" );                   System. out .println( x );        }   }   Exercise 2: Write a simple java program to tak...

Java Operators

In this lesson you are goin g to learn about operators in Java and also what are the different types of operators used in Java programming.   In our previous lesson we have learnt how to take user input in Java. We were performing different types of arithmetic operations in order to create a simple ration shop billing application which took different values as the user input and calculated total billing amount.   During the programming the billing application we used different signs like addition (+) , multiplication (*) etc. These signs are called operators in Java programming.   Types of Operators in Java There are five types of operators in Java. Arithmetic Operators Bitwise Operators Assignment Operators Comparison Operators Logical Operators 1.Java Arithmetic Operators Arithmetic operators are used to perform mathematical operations such addition, division, multiplication, subtraction and modulation. Let’s see the example of arithmetic operators in below:   ...