Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

A complete Introduction to All the Loops in Java

Last updated on Jun 06,2023 2.5K Views

Ravi Kiran
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning... Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning more about Data Science and Big-Data Hadoop.

Loops in Java, deliver the interpreter, the ability to make decisions by validating a particular value against a given test condition and execute a particular code segment for a specific number of times until the given condition is satisfied. The Loops in Java are listed as follows:

To understand the terminology of the Conditional Statements and Loops in Java, let us consider the following example.

Mr John would like to buy a brand new car. He likes three colours, namely Black, Red, and Blue. So, his condition to buy a car is that the car must be available in at least one of the three colours.

Car image He applied a decision loop in his mind and checked for the colours available in the dealership until his condition is satisfied. The same happens in the case of computers as well. They apply a condition and run the loop until the condition is satisfied.

Let us begin with Conditional Statements in Java. There are basically seven Control Statements in Java as mentioned below:

 

Conditional Statements 

They suggests the computer that it should carry out the execution of a particular segment of code, given the condition stated is true and valid. The Conditional Statements are classified as shown below

Loops-in-Java-Conditional-statements-Types-Edureka

 

If Condition

If Statement is a programming conditional statement that executes a code segment over a condition, provided if it is true and valid. Below is an example of an If statement.

//Find if the number is positive or negative.

Package ifloop;
public class ifloop {
public static void main(String[] args) {
        int number = -10;
        if (number > 0) {
              System.out.println("Number is positive.");
        }
        System.out.println("The number is negative.");
    }
}

//Output

The number is negative.

Discover how to create mobile apps that look and feel great on any platform with a comprehensive Flutter Course.

Else-If Condition

Else If Conditional Statement is used to execute one statement out of the two. The Conditional Statement executes the code segment provided is true and valid. Below is an example of an If statement.

//Find if the number is Even or Odd

package Esleifloop;
import java.util.Scanner;
public class elseifloop {
     public static void main(String[] args) {
          Scanner kb = new Scanner(System.in);
          System.out.println("Enter any integer value");
          int a=kb.nextInt();
          if(a%2==0){
                System.out.println("even number");
         } 
         else{
                System.out.println("odd number");
         }
     }
}

//Output

Enter any integer value
21
odd number

Example 2

//Find if the Year is a Leap Year or not

package Esleifloop;
import java.util.Scanner;
public class Leapyear {
	public static void main(String[] args) {    
	    Scanner kb = new Scanner(System.in);
        System.out.println("Enter any year");
        int year=kb.nextInt();   
	    if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){  
	        System.out.println("The Year you have entered is a Leap Year");  
	    }  
	    else{  
	        System.out.println("The Year you have entered is a not Leap Year");  
	    }  
	}
}
 

//Output

Enter any year
2019
The Year you have entered is a not Leap Year

 

Else-If Ladder

Else if Ladder is set of consecutive Else-If statements which are used to execute one true and valid statement out of a collection of given statements. Below is an example for Else-If Ladder.

//Selecting the Vehicle of your Choice.

package elseifladder;
import java.util.Scanner;
public class ladder {
public static void main(String[] args) {
      Scanner kb = new Scanner(System.in);
      System.out.println("Enter your chioce, 1 for the Sedan, 2 for SUV, 3 for Sports, 4 Cross Breed");
      int choice=kb.nextInt();
      if(choice==1){
            System.out.println("Sedan Class");
      }
      else if(choice==2){
            System.out.println("SUV Class");
      }
      else if(choice==3){
            System.out.println("Sports Class");
      }
      else if(choice==4){
            System.out.println("Cross-Breed Segment");
      }  
      else {
            System.out.println("Invalid Choice");
      }
   }
}

//Output

Enter your choice, 1 for the Sedan, 2 for SUV, 3 for Sports, 4 Cross-Breed

3
Sports Class

 

Nested If Condition

Nested-If is a conditional statement where one Else-If statement is embedded into another If statement. The following program is an example for Nested If condition.

//Find the greatest number out of the given three numbers

package nestedif;
public class nested {
      public static void main(String[] args) {
            int n1 = 20, n2 = 30, n3 = 10, greatest;
            if (n1 >= n2) {
                 if (n1 >= n3) {
                      greatest = n1;
                 }  
                 else {
                      greatest = n3;
                 }
            } 
            else {
                 if (n2 >= n3) {
                     greatest = n2;
                 } 
                 else {
                     greatest = n3;
                 }
            }
            System.out.println("Largest number is " + greatest);
      }
}

//Output

Largest number is 30

 

Ternary Operator

Ternary Operator is a conditional statement which has three arguments. First one is a conditional argument and the second is the result upon a true comparison, and the third is the result upon a false comparison.

//Find the greatest of the two numbers

package Ternary;
import java.util.Scanner;
public class Ternaryoperators {
     public static void main(String[] args) {
          Scanner kb = new Scanner(System.in);
          System.out.println("Enter any integer value to a");
          int a=kb.nextInt();
          System.out.println("Enter any integer value to b");
          int b=kb.nextInt();
          int greater = (a < b) ? a : b;
          System.out.println(greater);
     }
}

//Output

Enter any integer value to a
10
Enter any integer value to b
25
25

 

Switch Statements

Switch Statement is a multi-branch conditional statement. Basically, it has a conditional statement at the beginning of the switch case and the multiple possibilities are included inside the switch case. A case that finds a match is executed else a default statement is executed.

//Find the name of the month by giving an index number.

package Switch;
import java.util.Scanner;
public class switchdemo {
      public static void main(String[] args) {
            Scanner kb = new Scanner(System.in);
            System.out.println("Enter any month");
            int month=kb.nextInt();
            String name;
            switch (month) {
                    case 1: name = "January";
                                break;
                    case 2: name = "February";
                                break;
                    case 3: name = "March";
                                break;
                    case 4: name = "April";
                                break;
                    case 5: name = "May";
                                break;
                    case 6: name = "June";
                                break;
                    case 7: name = "July";
                                break;
                    case 8: name = "August";
                                break;
                    case 9: name = "September";
                                break;
                    case 10: name = "October";
                                break;
                    case 11: name = "November";
                                break;
                    case 12: name = "December";
                                break;
                    default: name = "Invalid Input";
                                break;
           }
      System.out.println(name);
      }
}

//Output

Enter any month
7
July

 

Break Statement

Break Statement is a control statement that is used inside a loop to immediately terminate and the program and resume the control at the next statement following in the loop.

//Break the control flow using a break statement

package breakstmt;
public class brkstmt {
	public static void main(String args[]) {
		int [] integerarray = {10, 20, 30, 40, 50, 60, 70, 80};
	    for(int num : integerarray ) {
	    	if( num == 40 ) {
	    		break;
	    	}
	    	System.out.print( num );
	    	System.out.print("n");	
	   	}
	 }
}

//Output

10
20
30

Loops in Java are basically divided into three types as described below:

Loops-in-Java-Types-Edureka

 

 

For Loop

For loop is a Control Flow Statement which allows you to execute a specific code segment for a finite number iterations. A for loop has three arguments, namely, initialization variable, Counter variable, and increment/decrement variable.

Below is the flow chart Related to For Loop.

Following code is an example for For Loop.

//Print the elements in an array using normal For Loop

package forloop;
public class forloop {
      public static void main(String[] args) {
            String[] arrData = {"JOHN", "JERRY", "RALPH", "JIM", "TOM"};
            System.out.println("Using normal For Loop:");
            for(int i=0; i< arrData.length; i++){
                    System.out.println(arrData[i]);
             }
      }
}

//Output

Using normal For Loop:
JOHN
JERRY
RALPH
JIM
TOM

 

Enhanced For Loop

Enhanced/Advanced For loop is similar to a for loop, but, it minimizes the code length and excludes counter variable and initialization variable. The control flows directly into the array/collection and executes operations on the elements by accessing their index.

Below is the flow chart Related to enhanced For Loop.

Following code is an example for Enhanced For Loop.

//Print the elements in an array using enhanced/advanced For Loop

package advforloop;
public class advforloop {
       public static void main(String[] args) {
             String[] arrData = {"JOHN", "JERRY", "RALPH", "JIM", "TOM"};
             System.out.println("Using Enhanced For Loop:");
             for (String strTemp : arrData){
                    System.out.println(strTemp);
             }
        }
}

//Output

Using Enhanced for loop:
JOHN
JERRY
RALPH
JIM
TOM

 

Nested For Loop

Nested for loop embeds another For loop within itself. The outer loop triggers the inner loop. The inner loop executes completely and then triggers the outer loop for updating the iteration. This process continues until the outer loop executes completely.

Below is the flow chart Related to Nested For Loop.

Loops-in-Java-Nested-for-loop-EdurekaFollowing code is an example for Nested For Loop.

//Print the elements in a two dimensional array using normal For Loop

package nestedforloop;
public class nested {
      public static void main(String[] args){
            int[][] arr = { { 1, 2 }, { 3, 4 } };
                   for (int i = 0; i < 2; i++)
                         System.out.println("Row" + i + " - ");
                         for (int j = 0; j < 2; j++)
                               System.out.println(arr[i][j]);
                         }
                   System.out.println("");
                   }
           }
}

//Output

Row 0 - 12
Row 1 - 34

 

While Loop

While loop is a Contol Flow Statement that executes itself repeatedly until a given boolean condition is satisfied. While loop can be considered as a repeating If statement.

Below is the flow chart for While Loop.

Loops-in-Java-While-loop-EdurekaFollowing code is an example for While Loop.

//Find if the number is a Prime Number or not using a While Loop

package whileloop;
import java.util.Scanner;
public class whiledemo {
      public static void main(String[] args) {
           Scanner kb = new Scanner(System.in);
           System.out.println("Enter any number");
           int num=kb.nextInt();
           int i = 2;
           boolean flag = false;
           while(i <= num/2)
          {
                if(num % i == 0)
                {
                      flag = true;
                      break;
                }
               ++i;
          }
          if (!flag)
               System.out.println(num + " is a prime number.");
          else
               System.out.println(num + " is not a prime number.");
          }
}

//Output

Enter any number
5
5 is a prime number.

 

Do While Loop

Do While loop is considered to be a conditional statement completely similar to a normal While loop. The only difference is that the Do While loop has the boolean/conditional statement is placed at the end of the loop. This makes the Do While loop to execute at least for once.

Below is the flow chart for Do While Loop.

Loops-in-Java-Do-While-loop-EdurekaFollowing code is an example for Do While Loop.

//Insert elements in an array and add them using normal While Loop

package dowhileloop;
import java.util.Scanner;
public class dowhile {
    public static void main(String[] args) {
        Double a, Summation = 0.0;
        Scanner kb = new Scanner(System.in);
        do {
                   System.out.print("Enter a number to perform addition and zero to exit: ");
                   a = kb.nextDouble();
                   Summation += a;
       } 
       while (a != 0.0);
       System.out.println("Sum of the numbers = " + Summation);
    }
}

//Output

Enter a number to perform addition and zero to exit: 10
Enter a number to perform addition and zero to exit: 20
Enter a number to perform addition and zero to exit: 30
Enter a number to perform addition and zero to exit: 40
Enter a number to perform addition and zero to exit: 0
Sum of the numbers = 100.0

 

Infinite Loop

Infinite Loop is not actually a practically designed loop. Instead, It is a situation where the condition of the loop fails and the execution persists until you stop it manually.

Loops-in-Java-Infinite-loop-Edureka

Following code is an example for Infinite Loop.

//Generate Infinite Loop

 
package infiniteloop; 
public class infinity { 
       public static void main(String[] args) { 
             int i=0; 
             while(true) { 
                     System.out.println("Edureka"); 
                     i++;
             } 
        } 
} 

//Output

Edureka
Edureka
Edureka
.............

With this, we come to an end of this article, I hope you have understood the Loops in Java and their implementation. If you find any queries related to this article, please write them down in the comment section below and we shall revert you back soon.

Now that you have understood basics of Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 19th October,2024

19th October

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 14th December,2024

14th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

A complete Introduction to All the Loops in Java

edureka.co