For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Looping statements in Java Programming help execute code blocks repeatedly based on conditions. Java offers four main loop types: while loop, do-while loop, for loop, and for-each loop, each with specific syntax and use cases for efficient programming.
Enhance your Java skills with expert-led training. Check out upGrad’s Software Engineering course and learn how to apply Java in real-world projects.
Looping statements in Java are essential control flow structures that execute a block of code repeatedly based on conditions. These statements help create efficient, clean code by eliminating redundancy.
Java loops optimize program performance by:
Different programming scenarios require different types of looping statements. The right loop choice depends on your specific requirements, expected iterations, and condition evaluation needs.
Loop Type | Initial Condition Check | Minimum Executions | Best For |
While | Before execution | 0 | Unknown iterations |
Do-While | After execution | 1 | Menu systems, input validation |
For | Before execution | 0 | Known iterations |
For-Each | N/A | 0 | Collection traversal |
Java developers are in high demand—especially with cloud and DevOps skills. Gain both with this Professional Certificate Program by upGrad.
Java offers four main types of looping statements in Java. Each has unique characteristics suited for different programming needs.
The while loop in Java is a pre-test loop that checks a condition before executing the loop body. It repeats until the condition becomes false.
while (condition) {
// Code to be executed
}
// Problem: Print numbers from 1 to 5 using while loop in Java
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1; // Initialize counter
while (i <= 5) { // Check condition before executing loop body
System.out.println(i); // Print current value
i++; // Increment counter
}
}
}
Output:
1
2
3
4
5
The while loop first checks if the condition is true, then executes the code block. The loop continues until the condition becomes false.
Take your Java knowledge to the next level. Explore the Executive Diploma in Data Science & AI by IIIT-B to dive into machine learning, AI, and analytics.
The do-while loop in Java is a post-test loop. It executes the code block at least once before checking the condition.
do {
// Code to be executed
} while (condition);
// Problem: Create a simple menu system that runs at least once
import java.util.Scanner;
public class DoWhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
// Display menu options
System.out.println("1. Option One");
System.out.println("2. Option Two");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt(); // Get user input
// Process user choice
System.out.println("You selected option " + choice);
} while (choice != 3); // Continue until user chooses to exit
System.out.println("Program terminated.");
scanner.close();
}
}
Output:
1. Option One
2. Option Two
3. Exit
Enter your choice: 1
You selected option 1
1. Option One
2. Option Two
3. Exit
Enter your choice: 3
You selected option 3
Program terminated.
The do-while loop guarantees that the menu is displayed at least once, making it perfect for menu-driven applications.
The for loop in Java provides a compact way to iterate when you know the number of iterations in advance.
for (initialization; condition; update) {
// Code to be executed
}
// Problem: Calculate sum of first n natural numbers
public class ForLoopExample {
public static void main(String[] args) {
int n = 5;
int sum = 0;
// For loop to calculate sum
for (int i = 1; i <= n; i++) {
sum += i; // Add current number to sum
}
System.out.println("Sum of first " + n + " natural numbers is: " + sum);
}
}
Output:
Sum of first 5 natural numbers is: 15
The for loop efficiently calculates the sum by initializing, checking conditions, and updating in a single line.
The for-each loop (enhanced for loop) in Java simplifies iterating through arrays and collections.
for (dataType item : array/collection) {
// Code to be executed
}
// Problem: Calculate average of elements in an array using for-each loop
public class ForEachLoopExample {
public static void main(String[] args) {
// Array of numbers
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;
int count = 0;
// For-each loop to iterate through array elements
for (int number : numbers) {
sum += number; // Add current element to sum
count++; // Count elements
}
// Calculate and display average
double average = (double) sum / count;
System.out.println("Average of array elements: " + average);
}
}
Output:
Average of array elements: 15.0
The for-each loop eliminates the need for index manipulation, making array traversal more readable and less error-prone.
Nested loops in Java occur when one loop is placed inside another. They're useful for working with multi-dimensional data structures or generating complex patterns.
// Problem: Print a multiplication table using nested loops
public class NestedLoopExample {
public static void main(String[] args) {
int size = 5; // Size of multiplication table
// Outer loop for rows
for (int i = 1; i <= size; i++) {
// Inner loop for columns
for (int j = 1; j <= size; j++) {
// Print product with formatting
System.out.printf("%4d", i * j);
}
System.out.println(); // New line after each row
}
}
}
Output:
The nested loops work together to create the multiplication table. The outer loop controls rows while the inner loop handles columns.
Infinite loops continue indefinitely without termination. They can be intentional (for server processes) or accidental (logic errors).
// Examples of infinite loops in Java
// 1. While loop infinite loop
while (true) {
// Code that never stops
// Must include a break statement somewhere to exit
if (exitCondition) {
break; // Safe exit strategy
}
}
// 2. For loop infinite loop
for (;;) {
// Code that runs forever
if (exitCondition) {
break; // Safe exit point
}
}
// 3. Do-while infinite loop
do {
// Code that always executes
if (exitCondition) {
break; // Exit mechanism
}
} while (true);
Issue | Example | Prevention |
Missing update | while (i < 10) { /* no i++ */ } | Always update counter variables |
Incorrect condition | while (i >= 0) { i++; } | Ensure condition can become false |
Logic errors | while (x != 10) { x += 2; } (when x starts at 1) | Test boundary conditions |
Float comparison | while (x != 1.0) { x += 0.1; } | Use tolerance ranges for floats |
To prevent unintended infinite loops:
Problem Statement: A data processing application needs to read a large CSV file line by line, parse each record, and perform data validation before storage.
// Problem: Process CSV file data line by line
public class FileProcessor {
public static void main(String[] args) {
String filePath = "customer_data.csv";
int validRecords = 0;
int invalidRecords = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
boolean isHeader = true;
// Use while loop to process unknown number of lines
while ((line = reader.readLine()) != null) {
if (isHeader) {
System.out.println("Processing file with header: " + line);
isHeader = false;
continue;
}
if (validateRecord(line)) {
processRecord(line);
validRecords++;
} else {
logInvalidRecord(line);
invalidRecords++;
}
}
System.out.println("Processing complete!");
System.out.println("Valid records: " + validRecords);
System.out.println("Invalid records: " + invalidRecords);
} catch (IOException e) {
System.err.println("Error processing file: " + e.getMessage());
}
}
private static boolean validateRecord(String record) {
// Validation logic here
return record.split(",").length >= 3;
}
private static void processRecord(String record) {
// Processing logic here
System.out.println("Processed: " + record.substring(0, Math.min(20, record.length())) + "...");
}
private static void logInvalidRecord(String record) {
// Logging logic here
System.out.println("Invalid record: " + record);
}
}
Output:
Processing file with header: id,name,email,purchase_amount
Processed: 1,Rajesh Kumar,raj...
Processed: 2,Priya Sharma,pri...
Invalid record: 3,Amit Patel
Processed: 4,Sunita Verma,sun...
Processing complete!
Valid records: 3
Invalid records: 1
This real-world example demonstrates using a while loop to process files of unknown size, a common application in data processing systems. The while loop is perfect here because we don't know how many records the file contains beforehand.
Problem Statement: A retail store needs to process their inventory items, calculate the value of each product line, and determine the total inventory value for accounting purposes.
// Problem: Process inventory items and calculate total value
public class InventorySystem {
public static void main(String[] args) {
// Product inventory (name, price, quantity)
String[] productNames = {"Laptop", "Phone", "Tablet", "Monitor", "Keyboard"};
double[] prices = {45999.99, 32999.99, 15499.99, 12499.99, 2999.99};
int[] quantities = {5, 10, 15, 8, 20};
double totalInventoryValue = 0;
System.out.println("INVENTORY REPORT");
System.out.println("---------------");
// Process each inventory item using for loop
for (int i = 0; i < productNames.length; i++) {
// Calculate value of current product line
double lineValue = prices[i] * quantities[i];
totalInventoryValue += lineValue;
// Print product details
System.out.printf("%-10s: %2d units × ₹%.2f = ₹%.2f\n",
productNames[i], quantities[i], prices[i], lineValue);
}
System.out.println("---------------");
System.out.printf("Total Inventory Value: ₹%.2f\n", totalInventoryValue);
}
}
Output:
INVENTORY REPORT
Laptop : 5 units × ₹45999.99 = ₹229999.95
Phone : 10 units × ₹32999.99 = ₹329999.90
Tablet : 15 units × ₹15499.99 = ₹232499.85
Monitor : 8 units × ₹12499.99 = ₹99999.92
Keyboard : 20 units × ₹2999.99 = ₹59999.80
Total Inventory Value: ₹952499.42
This real-world example demonstrates how loops efficiently process inventory data for business applications, calculating line values and totals without repetitive code.
Application | Best Loop Type | Example Use Case |
Array Processing | For/For-each | Iterating through elements |
Collection Traversal | For-each | Processing list items |
File Reading | While | Reading lines until EOF |
Menu Systems | Do-while | Displaying options at least once |
Database Operations | For | Processing query results |
Pattern Generation | Nested For | Creating visual patterns |
Event Handling | While | Waiting for user events |
Looping statements in Java are like tools in a toolbox - each has its own purpose. The while loop checks conditions first, do-while ensures code runs at least once, for loop is great when you know how many times to repeat, and for-each makes working with collections easy.
Learning these loops is like learning to ride different bicycles - once you master them, you can tackle any problem efficiently. The key is knowing which loop fits which situation. With practice, you'll write cleaner code that runs faster and solves complex problems step by step.
Next time you need to repeat code, remember that loops are your best friends. They save time, reduce mistakes, and make your programs work smarter, not harder. Start with simple examples, practice regularly, and soon you'll be looping like a pro!
Looping statements in Java are control flow structures that execute code repeatedly based on conditions. They reduce redundancy and increase efficiency in programs. Think of loops as shortcuts that help you avoid writing the same code multiple times, making your programs shorter and easier to maintain.
The while loop in Java executes code repeatedly as long as a condition remains true. It checks the condition before executing the loop body. It's like checking if it's raining before deciding to take an umbrella - if the condition is false initially, the loop code never runs even once.
The do-while loop in Java executes code at least once before checking the condition, making it ideal for scenarios requiring guaranteed execution. It's similar to trying a new recipe first and then deciding if you want to make it again so, you always cook it at least once regardless of your future decision.
The for-each loop in Java simplifies collection traversal by automatically accessing each element without requiring explicit indexing. It's like going through each book on your shelf without needing to count their positions & you just handle one book at a time until you've seen them all.
While loop checks conditions before execution and may skip entirely. Do-while executes at least once before checking conditions. This is similar to the difference between "Look before you leap" (while) and "Try it first, then decide" (do-while) approaches to problem-solving.
The do-while loop syntax in Java is:
do {
// Code to be executed
} while (condition);
Note that unlike other loops, do-while requires a semicolon after the condition. The structure ensures the code block executes before the condition is evaluated, guaranteeing at least one execution cycle.
Use for loops for known iterations, while loops for condition-based repetition, do-while for at-least-once execution, and for-each for collections. Your choice depends on whether you know the number of iterations in advance and whether the loop body should always execute at least once.
Yes, loops can be nested in Java by placing one loop inside another, allowing for complex iterations like matrix traversal or pattern generation. Think of nested loops like a clock - the minute hand (inner loop) completes a full cycle for each movement of the hour hand (outer loop).
Use the break statement to exit a loop immediately. The continue statement can skip the current iteration and proceed to the next one. These control statements give you fine-grained control over loop execution, letting you handle special cases or early termination conditions efficiently.
An infinite loop in Java continues indefinitely because its termination condition never becomes false. It can be created using while(true) or for(;;). While sometimes useful for server processes, infinite loops are often the result of logical errors and can cause programs to freeze or crash.
Optimize by minimizing operations inside loops, using appropriate collections, avoiding unnecessary object creation, and considering parallel streams. For very large datasets, consider batch processing, lazy evaluation techniques, or database-specific optimization strategies like indexed queries.
Your for loop might not execute if the initial condition is false. For example, for(int i=10; i<5; i++) will never run because 10 is not less than 5. Always check your loop conditions and initialization values, especially when loops appear to be skipped entirely during execution.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.