Loops in Java

Last updated on Dec 27 2022
Prabhas Ramanathan

In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true. There are three types of loops in Java.
• for loop
• while loop
• do-while loop

java 98

Table of Contents

Java For Loop vs While Loop vs Do While Loop

Comparison for loop while loop do while loop
Introduction The Java for loop is a control flow statement that iterates a part of the program’s multiple times. The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition. The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
When to use If the number of iteration is fixed, it is recommended to use for loop. If the number of iteration is not fixed, it is recommended to use while loop. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntax for(init;condition;incr/decr){  // code to be executed } while(condition){//code to be executed } do{//code to be executed  }while(condition);
Example //for loop  for(int i=1;i<=10;i++){  System.out.println(i);  } //while loop  int i=1;  while(i<=10){System.out.println(i);  i++;  } //do-while loop  int i=1;  do{System.out.println(i);  i++;  }while(i<=10);
Syntax for infinitive loop for(;;){  //code to be executed  } while(true){//code to be executed  } do{//code to be executed  }while(true);

Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
There are three types of for loops in java.
• Simple For Loop
• For-each or Enhanced For Loop
• Labeled For Loop

Java Simple For Loop

A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Syntax:

1. for(initialization;condition;incr/decr){ 
2. //statement or code to be executed 
3. }

Flowchart:

java 99

Example:

1. //Java Program to demonstrate the example of for loop 
2. //which prints table of 1 
3. public class ForExample { 
4. public static void main(String[] args) { 
5. //Code of Java for loop 
6. for(int i=1;i<=10;i++){ 
7. System.out.println(i); 
8. } 
9. } 
10. }

Output:
1
2
3
4
5
6
7
8
9
10

Java Nested For Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.
Example:

1. public class NestedForExample { 
2. public static void main(String[] args) { 
3. //loop of i 
4. for(int i=1;i<=3;i++){ 
5. //loop of j 
6. for(int j=1;j<=3;j++){ 
7. System.out.println(i+" "+j); 
8. }//end of i 
9. }//end of j 
10. } 
11. }

Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Example 1:

1. public class PyramidExample { 
2. public static void main(String[] args) { 
3. for(int i=1;i<=5;i++){ 
4. for(int j=1;j<=i;j++){ 
5. System.out.print("* "); 
6. } 
7. System.out.println();//new line 
8. } 
9. } 
10. }

Output:
*
* *
* * *
* * * *
* * * * *

Pyramid Example 2:

1. public class PyramidExample2 { 
2. public static void main(String[] args) { 
3. int term=6; 
4. for(int i=1;i<=term;i++){ 
5. for(int j=term;j>=i;j--){ 
6. System.out.print("* "); 
7. } 
8. System.out.println();//new line 
9. } 
10. } 
11. }

Output:
* * * * * *
* * * * *
* * * *
* * *
* *
*

Java for-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

1. for(Type var:array){ 
2. //code to be executed 
3. }

Example:

1. //Java For-each loop example which prints the 
2. //elements of the array 
3. public class ForEachExample { 
4. public static void main(String[] args) { 
5. //Declaring an array 
6. int arr[]={12,23,44,56,78}; 
7. //Printing array using for-each loop 
8. for(int i:arr){ 
9. System.out.println(i); 
10. } 
11. } 
12. }

Output:
12
23
44
56
78

Java LabeledFor Loop

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.

Syntax:

1. labelname: 
2. for(initialization;condition;incr/decr){ 
3. //code to be executed 
4. }

Example:

1. //A Java program to demonstrate the use of labeled for loop 
2. public class LabeledForExample { 
3. public static void main(String[] args) { 
4. //Using Label for outer and for loop 
5. aa: 
6. for(int i=1;i<=3;i++){ 
7. bb: 
8. for(int j=1;j<=3;j++){ 
9. if(i==2&&j==2){ 
10. break aa; 
11. } 
12. System.out.println(i+" "+j); 
13. } 
14. } 
15. } 
16. }

Output:
1 1
1 2
1 3
2 1

If you use break bb;, it will break inner loop only which is the default behavior of any loop.

1. public class LabeledForExample2 { 
2. public static void main(String[] args) { 
3. aa: 
4. for(int i=1;i<=3;i++){ 
5. bb: 
6. for(int j=1;j<=3;j++){ 
7. if(i==2&&j==2){ 
8. break bb; 
9. } 
10. System.out.println(i+" "+j); 
11. } 
12. } 
13. } 
14. }

Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Infinitive For Loop

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

1. for(;;){ 
2. //code to be executed 
3. }

Example:

1. //Java program to demonstrate the use of infinite for loop 
2. //which prints an statement 
3. public class ForExample { 
4. public static void main(String[] args) { 
5. //Using no condition in for loop 
6. for(;;){ 
7. System.out.println("infinitive loop"); 
8. } 
9. } 
10. }

Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop

ctrl+c
Now, you need to press ctrl+c to exit from the program.

Java While Loop

The Javawhile loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.

Syntax:

1. while(condition){ 
2. //code to be executed 
3. } 
java 100

Example:

1. public class WhileExample { 
2. public static void main(String[] args) { 
3. int i=1; 
4. while(i<=10){ 
5. System.out.println(i); 
6. i++; 
7. } 
8. } 
9. }

Output:
1
2
3
4
5
6
7
8
9
10

Java Infinitive While Loop

If you pass true in the while loop, it will be infinitive while loop.

Syntax:

1. while(true){ 
2. //code to be executed 
3. }

Example:

1. public class WhileExample2 { 
2. public static void main(String[] args) { 
3. while(true){ 
4. System.out.println("infinitive while loop"); 
5. } 
6. } 
7. }

Output:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

Java do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.

Syntax:

1. do{ 
2. //code to be executed 
3. }while(condition);

Example:

1. public class DoWhileExample { 
2. public static void main(String[] args) { 
3. int i=1; 
4. do{ 
5. System.out.println(i); 
6. i++; 
7. }while(i<=10); 
8. } 
9. }

 

Output:

1
2
3
4
5
6
7
8
9
10

Java Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

Syntax:

1. do{ 
2. //code to be executed 
3. }while(true);

Example:

1. public class DoWhileExample2 { 
2. public static void main(String[] args) { 
3. do{ 
4. System.out.println("infinitive do while loop"); 
5. }while(true); 
6. } 
7. }

Output:
infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

Java Break Statement

When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.

Syntax:

1. jump-statement;
2. break;

java 101

Java Break Statement with Loop

Example:

1. //Java Program to demonstrate the use of break statement 
2. //inside the for loop. 
3. public class BreakExample { 
4. public static void main(String[] args) { 
5. //using for loop 
6. for(int i=1;i<=10;i++){ 
7. if(i==5){ 
8. //breaking the loop 
9. break; 
10. } 
11. System.out.println(i); 
12. } 
13. } 
14. }

Output:

1
2
3
4

Java Break Statement with Inner Loop

It breaks inner loop only if you use break statement inside the inner loop.

Example:

1. //Java Program to illustrate the use of break statement 
2. //inside an inner loop 
3. public class BreakExample2 { 
4. public static void main(String[] args) { 
5. //outer loop 
6. for(int i=1;i<=3;i++){ 
7. //inner loop 
8. for(int j=1;j<=3;j++){ 
9. if(i==2&&j==2){ 
10. //using break statement inside the inner loop 
11. break; 
12. } 
13. System.out.println(i+" "+j); 
14. } 
15. } 
16. } 
17. }

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Break Statement with Labeled For Loop

We can use break statement with a label. This feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer loop or inner.

Example:

1. //Java Program to illustrate the use of continue statement 
2. //with label inside an inner loop to break outer loop 
3. public class BreakExample3 { 
4. public static void main(String[] args) { 
5. aa: 
6. for(int i=1;i<=3;i++){ 
7. bb: 
8. for(int j=1;j<=3;j++){ 
9. if(i==2&&j==2){ 
10. //using break statement with label 
11. break aa; 
12. } 
13. System.out.println(i+" "+j); 
14. } 
15. } 
16. } 
17. }

Output:

1 1
1 2
1 3
2 1

Java Break Statement in while loop

Example:

1. //Java Program to demonstrate the use of break statement 
2. //inside the while loop. 
3. public class BreakWhileExample { 
4. public static void main(String[] args) { 
5. //while loop 
6. int i=1; 
7. while(i<=10){ 
8. if(i==5){ 
9. //using break statement 
10. i++; 
11. break;//it will break the loop 
12. } 
13. System.out.println(i); 
14. i++; 
15. } 
16. } 
17. }

Output:

1
2
3
4

Java Break Statement in do-while loop

Example:

1. //Java Program to demonstrate the use of break statement 
2. //inside the Java do-while loop. 
3. public class BreakDoWhileExample { 
4. public static void main(String[] args) { 
5. //declaring variable 
6. int i=1; 
7. //do-while loop 
8. do{ 
9. if(i==5){ 
10. //using break statement 
11. i++; 
12. break;//it will break the loop 
13. } 
14. System.out.println(i); 
15. i++; 
16. }while(i<=10); 
17. } 
18. }

Output:

1
2
3
4

 

Java Break Statement with Switch

To understand the example of break with switch statement, please visit here: Java Switch Statement.

Java Continue Statement

The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.

Syntax:

1. jump-statement;
2. continue;

Java Continue Statement Example

Example:

1. //Java Program to demonstrate the use of continue statement 
2. //inside the for loop. 
3. public class ContinueExample { 
4. public static void main(String[] args) { 
5. //for loop 
6. for(int i=1;i<=10;i++){ 
7. if(i==5){ 
8. //using continue statement 
9. continue;//it will skip the rest statement 
10. } 
11. System.out.println(i); 
12. } 
13. } 
14. }

Output:

1
2
3
4
6
7
8
9
10

As you can see in the above output, 5 is not printed on the console. It is because the loop is continued when it reaches to 5.

Java Continue Statement with Inner Loop

It continues inner loop only if you use the continue statement inside the inner loop.

Example:

1. //Java Program to illustrate the use of continue statement 
2. //inside an inner loop 
3. public class ContinueExample2 { 
4. public static void main(String[] args) { 
5. //outer loop 
6. for(int i=1;i<=3;i++){ 
7. //inner loop 
8. for(int j=1;j<=3;j++){ 
9. if(i==2&&j==2){ 
10. //using continue statement inside inner loop 
11. continue; 
12. } 
13. System.out.println(i+" "+j); 
14. } 
15. } 
16. } 
17. }

Output:

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

Java Continue Statement with Labeled For Loop

We can use continute statement with a label. This feature is introduced since JDK 1.5. So, we can continue any loop in Java now whether it is outer loop or inner.

Example:

1. //Java Program to illustrate the use of continue statement 
2. //with label inside an inner loop to continue outer loop 
3. public class ContinueExample3 { 
4. public static void main(String[] args) { 
5. aa: 
6. for(int i=1;i<=3;i++){ 
7. bb: 
8. for(int j=1;j<=3;j++){ 
9. if(i==2&&j==2){ 
10. //using continue statement with label 
11. continue aa; 
12. } 
13. System.out.println(i+" "+j); 
14. } 
15. } 
16. } 
17. }

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Continue Statement in while loop

Example:

1. //Java Program to demonstrate the use of continue statement 
2. //inside the while loop. 
3. public class ContinueWhileExample { 
4. public static void main(String[] args) { 
5. //while loop 
6. int i=1; 
7. while(i<=10){ 
8. if(i==5){ 
9. //using continue statement 
10. i++; 
11. continue;//it will skip the rest statement 
12. } 
13. System.out.println(i); 
14. i++; 
15. } 
16. } 
17. }

Output:

1
2
3
4
6
7
8
9
10

Java Continue Statement in do-while loop

Example:

1. //Java Program to demonstrate the use of continue statement 
2. //inside the Java do-while loop. 
3. public class ContinueDoWhileExample { 
4. public static void main(String[] args) { 
5. //declaring variable 
6. int i=1; 
7. //do-while loop 
8. do{ 
9. if(i==5){ 
10. //using continue statement 
11. i++; 
12. continue;//it will skip the rest statement 
13. } 
14. System.out.println(i); 
15. i++; 
16. }while(i<=10); 
17. } 
18. }

Output:

1
2
3
4
6
7
8
9
10

So, this brings us to the end of blog. This Tecklearn ‘Loops in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Loops in Java"

Leave a Message

Your email address will not be published. Required fields are marked *